const fs = require('fs') const ExcelJS = require('exceljs') const csvPath = process.argv[2] || '历史SKU目录清单.csv' const xlsxPath = process.argv[3] || '历史SKU目录清单.xlsx' const windowsHeader = 'windows_path(Windows路径)' const prefix = process.argv[4] || '\\\\192.168.58.116\\yya\\品类二部\\建模原图' function parseCsvLine(line) { const result = [] let current = '' let inQuotes = false for (let i = 0; i < line.length; i += 1) { const char = line[i] const next = line[i + 1] if (char === '"') { if (inQuotes && next === '"') { current += '"' i += 1 } else { inQuotes = !inQuotes } continue } if (char === ',' && !inQuotes) { result.push(current) current = '' continue } current += char } result.push(current) return result } function escapeCsvCell(value) { const text = String(value ?? '') if (/[",\r\n]/.test(text)) { return `"${text.replace(/"/g, '""')}"` } return text } async function main() { const raw = fs.readFileSync(csvPath, 'utf8') const lines = raw.split(/\r?\n/).filter((line) => line.length > 0) const rows = lines.map(parseCsvLine) const header = rows[0] if (header.length > 0) { header[0] = String(header[0] || '').replace(/^\uFEFF/, '') } const windowsIndex = header.indexOf(windowsHeader) const kept = [header] for (let i = 1; i < rows.length; i += 1) { const row = rows[i] const windowsPath = String(row[windowsIndex] || '') if (windowsPath.startsWith(prefix)) { continue } kept.push(row) } fs.writeFileSync(csvPath, `\uFEFF${kept.map((row) => row.map(escapeCsvCell).join(',')).join('\r\n')}`, 'utf8') const workbook = new ExcelJS.Workbook() const worksheet = await workbook.csv.readFile(csvPath) worksheet.name = 'SKU目录' worksheet.views = [{ state: 'frozen', ySplit: 1 }] worksheet.columns.forEach((column) => { let maxLength = String(column.header || '').length column.eachCell({ includeEmpty: true }, (cell) => { const length = String(cell.value ?? '').length if (length > maxLength) { maxLength = length } }) column.width = Math.min(90, Math.max(12, maxLength + 2)) }) await workbook.xlsx.writeFile(xlsxPath) console.log('done') } main().catch((error) => { console.error(error) process.exit(1) })