diff --git a/data.xlsx b/data.xlsx new file mode 100644 index 0000000..6883859 Binary files /dev/null and b/data.xlsx differ diff --git a/json-to-xlsx.js b/json-to-xlsx.js new file mode 100644 index 0000000..5afa8e9 --- /dev/null +++ b/json-to-xlsx.js @@ -0,0 +1,64 @@ + +import fs from 'fs/promises'; +import ExcelJS from 'exceljs'; + +async function jsonToXlsx() { + try { + const jsonFilePath = './data.json'; + const xlsxFilePath = './data.xlsx'; + + // Read and parse the JSON file + const jsonData = await fs.readFile(jsonFilePath, 'utf-8'); + const records = JSON.parse(jsonData); + + if (records.length === 0) { + console.log('data.json 文件为空,没有数据可转换为 XLSX。'); + return; + } + + // Create a new workbook and a worksheet + const workbook = new ExcelJS.Workbook(); + const worksheet = workbook.addWorksheet('Data'); + + // Define columns based on the keys of the first record + const headers = Object.keys(records[0]); + worksheet.columns = headers.map(key => ({ + header: key, + key: key, + width: key.includes('地址') || key.includes('链接') ? 40 : 20 // Make address and link columns wider + })); + + // Add the records as rows + worksheet.addRows(records); + + // Style the header + worksheet.getRow(1).eachCell(cell => { + cell.font = { bold: true }; + cell.fill = { + type: 'pattern', + pattern:'solid', + fgColor:{argb:'FFDDDDDD'} + }; + cell.alignment = { vertical: 'middle', horizontal: 'center' }; + }); + + // Auto-filter on the header row + worksheet.autoFilter = { + from: 'A1', + to: { + row: 1, + column: headers.length + } + }; + + // Write to file + await workbook.xlsx.writeFile(xlsxFilePath); + console.log(`成功将 ${jsonFilePath} 转换为 ${xlsxFilePath}`); + console.log('XLSX 文件已创建,您现在可以在其中进行筛选和排序。'); + + } catch (error) { + console.error('转换 JSON 到 XLSX 时发生错误:', error.message); + } +} + +jsonToXlsx();