609 lines
25 KiB
JavaScript
609 lines
25 KiB
JavaScript
// ==UserScript==
|
|
// @name Mysteel 钢铁价格提取器
|
|
// @namespace http://tampermonkey.net/
|
|
// @version 6.5
|
|
// @description 合并列表页与详情页的抓取逻辑,统一透视表导出csv,支持多维筛选及本地缓存,加入登录状态拦截
|
|
// @author ali
|
|
// @mail solitude@hraulein.com
|
|
// @match *://*.mysteel.com/market/*
|
|
// @match *://*.mysteel.com/m/*
|
|
// @grant none
|
|
// @require https://cdn.jsdelivr.net/npm/xlsx@0.18.5/dist/xlsx.full.min.js
|
|
// ==/UserScript==
|
|
|
|
(function () {
|
|
'use strict';
|
|
|
|
// 判断当前页面类型
|
|
const isListPage = window.location.href.includes('/market/');
|
|
const isDetailPage = window.location.href.includes('/m/');
|
|
|
|
// 预设筛选常量
|
|
const FILTER_OPTIONS = {
|
|
names: ['高线', '螺纹钢', '盘螺'],
|
|
specs: ['Φ6', 'Φ8', 'Φ8-10', 'Φ10', 'Φ12', 'Φ14', 'Φ16', 'Φ18', 'Φ20', 'Φ22', 'Φ25', 'Φ28', 'Φ32', 'Φ36', 'Φ36-40', 'Φ40'],
|
|
materials: ['HPB300', 'HRB400', 'HRB400E', 'HRB500E']
|
|
};
|
|
|
|
// ==========================================
|
|
// 状态守卫区
|
|
// ==========================================
|
|
|
|
// 校验登录状态
|
|
function isUserLoggedIn() {
|
|
// 未登录时页面存在带有 'topbar-nav-login' 类的元素
|
|
const loginElement = document.querySelector('.topbar-nav-login');
|
|
if (loginElement) {
|
|
return false; // 存在“登录”按钮,说明未登录
|
|
}
|
|
return true; // 已登录
|
|
}
|
|
|
|
// 读取本地缓存的筛选条件
|
|
function loadSavedFilters() {
|
|
const defaultFilters = { names: [], specs: [], materials: [], exportFormat: 'csv', exportFilename: '钢材透视价格表' };
|
|
const saved = localStorage.getItem('mysteel_filters');
|
|
if (saved) {
|
|
try {
|
|
return { ...defaultFilters, ...JSON.parse(saved) };
|
|
} catch (e) {
|
|
console.error('解析缓存筛选条件失败', e);
|
|
}
|
|
}
|
|
return defaultFilters;
|
|
}
|
|
|
|
// 保存筛选条件到本地缓存
|
|
function saveFiltersToLocal(filters) {
|
|
localStorage.setItem('mysteel_filters', JSON.stringify(filters));
|
|
}
|
|
|
|
// 获取当前活动筛选条件 (直接从 DOM 获取)
|
|
function getCurrentFilters() {
|
|
const formatEl = document.getElementById('ms-filter-format');
|
|
const filenameEl = document.getElementById('ms-filter-filename');
|
|
return {
|
|
names: Array.from(document.querySelectorAll('input[name="ms-filter-names"]:checked')).map(el => el.value),
|
|
specs: Array.from(document.querySelectorAll('input[name="ms-filter-specs"]:checked')).map(el => el.value),
|
|
materials: Array.from(document.querySelectorAll('input[name="ms-filter-materials"]:checked')).map(el => el.value),
|
|
exportFormat: formatEl ? formatEl.value : 'csv',
|
|
exportFilename: filenameEl ? filenameEl.value : '钢材透视价格表'
|
|
};
|
|
}
|
|
|
|
// ==========================================
|
|
// 构建交互 UI
|
|
// ==========================================
|
|
function injectUI() {
|
|
if (document.getElementById('mysteel-tool-container')) return;
|
|
|
|
const savedFilters = loadSavedFilters();
|
|
|
|
const container = document.createElement('div');
|
|
container.id = 'mysteel-tool-container';
|
|
Object.assign(container.style, {
|
|
position: 'fixed', bottom: '50px', right: '50px',
|
|
display: 'flex', alignItems: 'flex-end', gap: '10px',
|
|
zIndex: '99999', fontFamily: 'sans-serif'
|
|
});
|
|
|
|
// --- 主按钮 ---
|
|
const btn = document.createElement('button');
|
|
btn.id = 'mysteel-action-btn';
|
|
// 根据页面类型设定按钮文字
|
|
btn.innerText = isListPage ? '🚀 批量提取并透视导出' : '📊 导出当日数据(透视版)';
|
|
|
|
Object.assign(btn.style, {
|
|
padding: '12px 24px',
|
|
backgroundColor: isListPage ? '#fa541c' : '#1890ff',
|
|
color: '#fff',
|
|
border: 'none', borderRadius: '6px', fontSize: '16px', fontWeight: 'bold',
|
|
boxShadow: '0 4px 12px rgba(0,0,0,0.2)', cursor: 'pointer', transition: '0.3s'
|
|
});
|
|
|
|
btn.onmouseover = () => btn.style.backgroundColor = isListPage ? '#ff7875' : '#40a9ff';
|
|
btn.onmouseout = () => btn.style.backgroundColor = isListPage ? '#fa541c' : '#1890ff';
|
|
|
|
// 绑定对应的执行引擎
|
|
if (isListPage) {
|
|
btn.addEventListener('click', startBatchProcess);
|
|
} else if (isDetailPage) {
|
|
btn.addEventListener('click', startSingleProcess);
|
|
}
|
|
|
|
// --- 齿轮图标 ---
|
|
const gearBtn = document.createElement('div');
|
|
gearBtn.innerHTML = '⚙️';
|
|
Object.assign(gearBtn.style, {
|
|
width: '46px', height: '46px', backgroundColor: '#fff',
|
|
borderRadius: '50%', display: 'flex', justifyContent: 'center', alignItems: 'center',
|
|
fontSize: '24px', boxShadow: '0 4px 12px rgba(0,0,0,0.2)', cursor: 'pointer',
|
|
userSelect: 'none'
|
|
});
|
|
|
|
// --- 悬浮状态提示面板 ---
|
|
const tooltip = document.createElement('div');
|
|
Object.assign(tooltip.style, {
|
|
display: 'none', position: 'absolute', bottom: '60px', right: '0',
|
|
backgroundColor: 'rgba(0,0,0,0.85)', color: '#fff', padding: '12px',
|
|
borderRadius: '6px', fontSize: '13px', width: 'max-content',
|
|
maxWidth: '300px', lineHeight: '1.5', pointerEvents: 'none',
|
|
boxShadow: '0 4px 12px rgba(0,0,0,0.1)'
|
|
});
|
|
|
|
// --- 高级筛选配置面板 ---
|
|
const panel = document.createElement('div');
|
|
panel.id = 'mysteel-filter-panel';
|
|
Object.assign(panel.style, {
|
|
display: 'none', position: 'absolute', bottom: '60px', right: '0',
|
|
backgroundColor: '#fff', padding: '20px', borderRadius: '8px',
|
|
boxShadow: '0 4px 24px rgba(0,0,0,0.2)', width: '360px',
|
|
color: '#333', border: '1px solid #eee'
|
|
});
|
|
|
|
// 动态生成带有缓存状态的 Checkbox HTML
|
|
const buildCheckboxes = (groupName, options) => {
|
|
return options.map(opt => {
|
|
const isChecked = savedFilters[groupName].includes(opt) ? 'checked' : '';
|
|
return `
|
|
<label style="display:inline-flex; align-items:center; margin-right:12px; margin-bottom:8px; font-size:13px; cursor:pointer;">
|
|
<input type="checkbox" name="ms-filter-${groupName}" value="${opt}" style="margin-right:4px;" ${isChecked}> ${opt}
|
|
</label>
|
|
`;
|
|
}).join('');
|
|
};
|
|
|
|
panel.innerHTML = `
|
|
<div style="font-size:16px; font-weight:bold; margin-bottom:15px; border-bottom:1px solid #eee; padding-bottom:8px;">高级筛选配置</div>
|
|
<div style="margin-bottom:12px;">
|
|
<div style="font-size:13px; color:#333; font-weight:bold; margin-bottom:6px;">类别:</div>
|
|
<div style="display:flex; flex-wrap:wrap;">${buildCheckboxes('names', FILTER_OPTIONS.names)}</div>
|
|
</div>
|
|
<div style="margin-bottom:12px;">
|
|
<div style="font-size:13px; color:#333; font-weight:bold; margin-bottom:6px;">线径:</div>
|
|
<div style="display:flex; flex-wrap:wrap;">${buildCheckboxes('specs', FILTER_OPTIONS.specs)}</div>
|
|
</div>
|
|
<div style="margin-bottom:15px;">
|
|
<div style="font-size:13px; color:#333; font-weight:bold; margin-bottom:6px;">材质:</div>
|
|
<div style="display:flex; flex-wrap:wrap;">${buildCheckboxes('materials', FILTER_OPTIONS.materials)}</div>
|
|
</div>
|
|
<div style="font-size:16px; font-weight:bold; margin-bottom:15px; border-bottom:1px solid #eee; padding-bottom:8px;">导出配置</div>
|
|
<div style="margin-bottom:12px; display:flex; gap:10px; align-items:flex-end;">
|
|
<div style="flex:1;">
|
|
<div style="font-size:13px; color:#333; font-weight:bold; margin-bottom:6px;">导出格式:</div>
|
|
<select id="ms-filter-format" style="width:100%; padding:4px 8px; font-size:13px; height:28px; box-sizing:border-box; border:1px solid #ccc; border-radius:4px; outline:none;">
|
|
<option value="csv" ${savedFilters.exportFormat === 'csv' ? 'selected' : ''}>CSV</option>
|
|
<option value="xlsx" ${savedFilters.exportFormat === 'xlsx' ? 'selected' : ''}>XLSX</option>
|
|
</select>
|
|
</div>
|
|
<div style="flex:2;">
|
|
<div style="font-size:13px; color:#333; font-weight:bold; margin-bottom:6px;">自定义文件名称:</div>
|
|
<input type="text" id="ms-filter-filename" value="${savedFilters.exportFilename || '钢材透视价格表'}" style="width:100%; padding:4px 8px; font-size:13px; height:28px; box-sizing:border-box; border:1px solid #ccc; border-radius:4px; outline:none;">
|
|
</div>
|
|
</div>
|
|
<button id="ms-close-panel-btn" style="width:100%; padding:8px; background:#1890ff; color:#fff; border:none; border-radius:4px; cursor:pointer; font-weight:bold;">保存并关闭</button>
|
|
`;
|
|
|
|
// --- UI 交互逻辑 ---
|
|
gearBtn.addEventListener('mouseenter', () => {
|
|
if (panel.style.display === 'block') return;
|
|
const f = getCurrentFilters();
|
|
const formatF = (arr) => arr.length > 0 ? arr.join(', ') : '全部';
|
|
tooltip.innerHTML = `
|
|
<div style="font-weight:bold; margin-bottom:4px;">当前筛选状态:</div>
|
|
<div>类别:${formatF(f.names)}</div>
|
|
<div>线径:${formatF(f.specs)}</div>
|
|
<div>材质:${formatF(f.materials)}</div>
|
|
<div style="margin-top:4px; border-top:1px solid rgba(255,255,255,0.2); padding-top:4px;">
|
|
格式:${f.exportFormat.toUpperCase()}
|
|
</div>
|
|
`;
|
|
tooltip.style.display = 'block';
|
|
});
|
|
|
|
gearBtn.addEventListener('mouseleave', () => {
|
|
tooltip.style.display = 'none';
|
|
});
|
|
|
|
gearBtn.addEventListener('click', () => {
|
|
tooltip.style.display = 'none';
|
|
panel.style.display = panel.style.display === 'none' ? 'block' : 'none';
|
|
});
|
|
|
|
// 组装 DOM
|
|
container.appendChild(panel);
|
|
container.appendChild(tooltip);
|
|
container.appendChild(btn);
|
|
container.appendChild(gearBtn);
|
|
document.body.appendChild(container);
|
|
|
|
// 绑定保存关闭按钮事件
|
|
document.getElementById('ms-close-panel-btn').addEventListener('click', () => {
|
|
const active = getCurrentFilters();
|
|
saveFiltersToLocal(active); // 写入 localStorage
|
|
panel.style.display = 'none';
|
|
showToast('配置已保存', 'success');
|
|
});
|
|
}
|
|
|
|
// ==========================================
|
|
// 引擎 A: 详情页单页抓取
|
|
// ==========================================
|
|
function startSingleProcess() {
|
|
// 🔒 登录状态守卫拦截
|
|
if (!isUserLoggedIn()) {
|
|
showToast('请登录 Mysteel 账号后重试!', 'error');
|
|
return;
|
|
}
|
|
|
|
const btn = document.getElementById('mysteel-action-btn');
|
|
const originalText = btn.innerText;
|
|
btn.innerText = '正在提取...';
|
|
btn.disabled = true;
|
|
|
|
try {
|
|
// 提取日期:从 <span class="content-info-text publish-time"> 提取
|
|
const dateEl = document.querySelector('.content-info-text.publish-time');
|
|
if (!dateEl) {
|
|
showToast('未找到页面的发布时间,请确认当前网页结构!', 'error');
|
|
return;
|
|
}
|
|
// 提取 "2026-07-24 17:41" 中的 "2026-07-24"
|
|
const dateStr = dateEl.innerText.trim().split(' ')[0];
|
|
|
|
const activeFilters = getCurrentFilters();
|
|
|
|
// 直接读取当前 DOM 树中的数据
|
|
const flatData = extractDataFromDoc(document, dateStr, activeFilters);
|
|
|
|
if (flatData.length > 0) {
|
|
generatePivotExport(flatData, '单日');
|
|
} else {
|
|
showToast('根据当前筛选条件,未提取到有效数据!', 'warning');
|
|
}
|
|
} catch (error) {
|
|
if (error.message === 'NO_PERMISSION') {
|
|
showToast('当前账号暂无权限查看价格数据,请确认是否已购买或开通相关权限!', 'warning');
|
|
} else {
|
|
console.error('详情页提取出错:', error);
|
|
showToast('发生错误,请查看控制台日志。', 'error');
|
|
}
|
|
} finally {
|
|
btn.innerText = originalText;
|
|
btn.disabled = false;
|
|
}
|
|
}
|
|
|
|
// ==========================================
|
|
// 引擎 B: 列表页批量抓取
|
|
// ==========================================
|
|
async function startBatchProcess() {
|
|
// 🔒 登录状态守卫拦截
|
|
if (!isUserLoggedIn()) {
|
|
showToast('请登录 Mysteel 账号后重试!', 'error');
|
|
return;
|
|
}
|
|
|
|
const btn = document.getElementById('mysteel-action-btn');
|
|
const originalText = btn.innerText;
|
|
btn.disabled = true;
|
|
btn.style.backgroundColor = '#ccc';
|
|
|
|
try {
|
|
btn.innerText = '正在分析列表...';
|
|
const targetLinks = getTargetLinks();
|
|
if (targetLinks.length === 0) {
|
|
showToast('未发现符合条件的链接!', 'warning');
|
|
return;
|
|
}
|
|
|
|
let flatData = [];
|
|
const activeFilters = getCurrentFilters();
|
|
|
|
// 顺序加载每一个页面
|
|
for (let i = 0; i < targetLinks.length; i++) {
|
|
const linkObj = targetLinks[i];
|
|
btn.innerText = `正在渲染: ${linkObj.date} (${i + 1}/${targetLinks.length})...`;
|
|
|
|
try {
|
|
const doc = await getRenderedDocViaIframe(linkObj.url);
|
|
if (doc) {
|
|
const dailyData = extractDataFromDoc(doc, linkObj.date, activeFilters);
|
|
if (dailyData.length > 0) {
|
|
flatData = flatData.concat(dailyData);
|
|
}
|
|
} else {
|
|
showToast(`日期 ${linkObj.date} 页面加载失败或因跨域重定向,已跳过`, 'warning');
|
|
}
|
|
} catch (err) {
|
|
if (err.message === 'NO_PERMISSION') throw err;
|
|
console.error(`渲染 ${linkObj.date} 失败:`, err);
|
|
}
|
|
}
|
|
|
|
btn.innerText = '正在生成数据透视表...';
|
|
|
|
if (flatData.length > 0) {
|
|
generatePivotExport(flatData, '批量');
|
|
} else {
|
|
showToast('根据当前筛选条件,未能提取到任何数据!', 'warning');
|
|
}
|
|
|
|
} catch (error) {
|
|
if (error.message === 'NO_PERMISSION') {
|
|
showToast('当前账号暂无权限查看价格数据,请确认是否已购买或开通相关权限!', 'warning');
|
|
} else {
|
|
console.error('批量处理出错:', error);
|
|
showToast('发生错误,请查看控制台。', 'error');
|
|
}
|
|
} finally {
|
|
btn.innerText = originalText;
|
|
btn.disabled = false;
|
|
btn.style.backgroundColor = '#fa541c';
|
|
}
|
|
}
|
|
|
|
// ==========================================
|
|
// 公共组件区
|
|
// ==========================================
|
|
|
|
// Toast 提示组件
|
|
function showToast(message, type = 'info') {
|
|
const toast = document.createElement('div');
|
|
toast.innerText = message;
|
|
|
|
let bgColor = '#1890ff';
|
|
if (type === 'error') bgColor = '#ff4d4f';
|
|
else if (type === 'success') bgColor = '#52c41a';
|
|
else if (type === 'warning') bgColor = '#faad14';
|
|
|
|
Object.assign(toast.style, {
|
|
position: 'fixed',
|
|
top: '30vh',
|
|
left: '50%',
|
|
transform: 'translateX(-50%)',
|
|
backgroundColor: bgColor,
|
|
color: '#fff',
|
|
padding: '12px 24px',
|
|
borderRadius: '4px',
|
|
boxShadow: '0 4px 12px rgba(0,0,0,0.15)',
|
|
zIndex: '999999',
|
|
fontSize: '14px',
|
|
whiteSpace: 'pre-wrap',
|
|
opacity: '0',
|
|
transition: 'opacity 0.3s, top 0.3s',
|
|
pointerEvents: 'none',
|
|
textAlign: 'center',
|
|
lineHeight: '1.5'
|
|
});
|
|
|
|
document.body.appendChild(toast);
|
|
|
|
// 动画显示
|
|
requestAnimationFrame(() => {
|
|
toast.style.opacity = '1';
|
|
toast.style.top = '33vh';
|
|
});
|
|
|
|
// 定时移除
|
|
setTimeout(() => {
|
|
toast.style.opacity = '0';
|
|
toast.style.top = '30vh';
|
|
setTimeout(() => {
|
|
if (toast.parentNode) {
|
|
toast.parentNode.removeChild(toast);
|
|
}
|
|
}, 300);
|
|
}, 5000);
|
|
}
|
|
|
|
// 获取列表页的日期链接
|
|
function getTargetLinks() {
|
|
const listItems = document.querySelectorAll('#articleList .nlist li');
|
|
const dailyMap = new Map();
|
|
|
|
listItems.forEach(li => {
|
|
const dateSpan = li.querySelector('.date');
|
|
const aTag = li.querySelector('a');
|
|
|
|
if (!dateSpan || !aTag) return;
|
|
|
|
const text = aTag.innerText.trim();
|
|
const href = aTag.href;
|
|
|
|
if (text.includes('工程') || text.includes('采购')) return;
|
|
|
|
const dateTimeStr = dateSpan.innerText.trim();
|
|
const [date, time] = dateTimeStr.split(' ');
|
|
|
|
if (date && time && href.includes('mysteel.com')) {
|
|
if (!dailyMap.has(date) || time > dailyMap.get(date).time) {
|
|
dailyMap.set(date, { date, time, url: href, title: text });
|
|
}
|
|
}
|
|
});
|
|
|
|
return Array.from(dailyMap.values()).sort((a, b) => b.date.localeCompare(a.date));
|
|
}
|
|
|
|
// Iframe 静默渲染引擎
|
|
async function getRenderedDocViaIframe(url) {
|
|
return new Promise((resolve) => {
|
|
const iframe = document.createElement('iframe');
|
|
Object.assign(iframe.style, {
|
|
width: '0px', height: '0px', visibility: 'hidden', position: 'absolute', border: 'none'
|
|
});
|
|
iframe.src = url;
|
|
|
|
iframe.onload = () => {
|
|
setTimeout(() => {
|
|
try {
|
|
const iframeDoc = iframe.contentDocument || iframe.contentWindow.document;
|
|
resolve(iframeDoc);
|
|
} catch (e) {
|
|
resolve(null);
|
|
} finally {
|
|
document.body.removeChild(iframe);
|
|
}
|
|
}, 2500);
|
|
};
|
|
|
|
iframe.onerror = () => {
|
|
document.body.removeChild(iframe);
|
|
resolve(null);
|
|
};
|
|
|
|
document.body.appendChild(iframe);
|
|
});
|
|
}
|
|
|
|
// 核心提取与数据清洗过滤引擎
|
|
function extractDataFromDoc(doc, dateStr, filters) {
|
|
const targetTable = doc.getElementById('marketTable');
|
|
if (!targetTable) return [];
|
|
|
|
const tbody = targetTable.querySelector('tbody');
|
|
if (!tbody) return [];
|
|
const rows = tbody.querySelectorAll('tr');
|
|
|
|
const dataMap = new Map();
|
|
|
|
for (let row of rows) {
|
|
if (row.style.display === 'none' || !row.hasAttribute('table-row-id')) continue;
|
|
|
|
const tdBreed = row.querySelector('td[data-type="breed"]');
|
|
const tdSpec = row.querySelector('td[data-type="spec"]');
|
|
const tdMaterial = row.querySelector('td[data-type="material"]');
|
|
const tdPrice = row.querySelector('td[data-type="price"]');
|
|
|
|
if (!tdBreed || !tdSpec || !tdMaterial || !tdPrice) continue;
|
|
|
|
if (tdPrice.querySelector('.icon-key')) {
|
|
throw new Error('NO_PERMISSION');
|
|
}
|
|
|
|
const cleanText = (element) => {
|
|
let clone = element.cloneNode(true);
|
|
let childIcons = clone.querySelectorAll('a, img, div');
|
|
childIcons.forEach(icon => icon.remove());
|
|
return clone.innerText.replace(/[\r\n\t]/g, '').trim();
|
|
};
|
|
|
|
const name = cleanText(tdBreed);
|
|
const spec = cleanText(tdSpec);
|
|
const material = cleanText(tdMaterial);
|
|
|
|
// 筛选校验拦截
|
|
if (filters.names.length > 0 && !filters.names.includes(name)) continue;
|
|
if (filters.specs.length > 0 && !filters.specs.includes(spec)) continue;
|
|
if (filters.materials.length > 0 && !filters.materials.includes(material)) continue;
|
|
|
|
const priceStr = tdPrice.innerText.replace(/,/g, '').trim();
|
|
const currentPrice = parseFloat(priceStr);
|
|
|
|
if (!name || isNaN(currentPrice)) continue;
|
|
|
|
const uniqueKey = `${name}_${spec}_${material}`;
|
|
|
|
if (!dataMap.has(uniqueKey) || currentPrice < dataMap.get(uniqueKey).priceNum) {
|
|
dataMap.set(uniqueKey, {
|
|
date: dateStr,
|
|
name: name,
|
|
spec: spec,
|
|
material: material,
|
|
priceNum: currentPrice
|
|
});
|
|
}
|
|
}
|
|
return Array.from(dataMap.values());
|
|
}
|
|
|
|
// 数据透视与生成 CSV 或 XLSX
|
|
function generatePivotExport(flatData, filePrefix) {
|
|
// 1. 提取独立日期并升序排列
|
|
const uniqueDates = [...new Set(flatData.map(d => d.date))].sort((a, b) => a.localeCompare(b));
|
|
|
|
// 日期格式化:将 "2026-07-24" 转为 "7/24"
|
|
const formatHeaderDate = (dStr) => {
|
|
const parts = dStr.split('-');
|
|
if (parts.length === 3) {
|
|
return `${parseInt(parts[1], 10)}/${parseInt(parts[2], 10)}`;
|
|
}
|
|
return dStr;
|
|
};
|
|
|
|
const dateHeaders = uniqueDates.map(formatHeaderDate);
|
|
|
|
// 2. 将扁平数据转为透视结构的 Map
|
|
const pivotMap = new Map();
|
|
flatData.forEach(item => {
|
|
const key = `${item.name}_${item.spec}_${item.material}`;
|
|
if (!pivotMap.has(key)) {
|
|
pivotMap.set(key, {
|
|
name: item.name,
|
|
spec: item.spec,
|
|
material: item.material,
|
|
pricesByDate: {}
|
|
});
|
|
}
|
|
pivotMap.get(key).pricesByDate[item.date] = item.priceNum;
|
|
});
|
|
|
|
// 读取导出设置
|
|
const filters = getCurrentFilters();
|
|
const exportFormat = filters.exportFormat || 'csv';
|
|
const exportFilename = filters.exportFilename || '钢材透视价格表';
|
|
const d = new Date();
|
|
const dateStr = `${d.getFullYear()}${(d.getMonth() + 1).toString().padStart(2, '0')}${d.getDate().toString().padStart(2, '0')}`;
|
|
const finalFilename = `${exportFilename}_${filePrefix}_${dateStr}`;
|
|
|
|
if (exportFormat === 'xlsx' && typeof XLSX !== 'undefined') {
|
|
const aoa = [];
|
|
aoa.push(['类别', '线径', '材质', ...dateHeaders]);
|
|
pivotMap.forEach(row => {
|
|
const rowData = [row.name, row.spec, row.material];
|
|
uniqueDates.forEach(date => {
|
|
rowData.push(row.pricesByDate[date] ? row.pricesByDate[date] : '');
|
|
});
|
|
aoa.push(rowData);
|
|
});
|
|
const ws = XLSX.utils.aoa_to_sheet(aoa);
|
|
const wb = XLSX.utils.book_new();
|
|
XLSX.utils.book_append_sheet(wb, ws, "Sheet1");
|
|
XLSX.writeFile(wb, `${finalFilename}.xlsx`);
|
|
} else {
|
|
// 3. 拼接 CSV 内容
|
|
let csvContent = '\uFEFF';
|
|
csvContent += `类别,线径,材质,${dateHeaders.join(',')}\n`;
|
|
|
|
pivotMap.forEach(row => {
|
|
let rowText = `"${row.name}","${row.spec}","${row.material}"`;
|
|
uniqueDates.forEach(date => {
|
|
const price = row.pricesByDate[date] ? row.pricesByDate[date] : '';
|
|
rowText += `,"${price}"`;
|
|
});
|
|
csvContent += rowText + '\n';
|
|
});
|
|
|
|
// 4. 触发下载
|
|
const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
|
|
const url = URL.createObjectURL(blob);
|
|
const link = document.createElement('a');
|
|
|
|
link.setAttribute('href', url);
|
|
link.setAttribute('download', `${finalFilename}.csv`);
|
|
|
|
document.body.appendChild(link);
|
|
link.click();
|
|
|
|
document.body.removeChild(link);
|
|
URL.revokeObjectURL(url);
|
|
}
|
|
}
|
|
|
|
// 延时加载注入
|
|
window.addEventListener('load', injectUI);
|
|
setTimeout(injectUI, 2000);
|
|
setTimeout(injectUI, 5000);
|
|
|
|
})(); |