jsonToXlsx
This commit is contained in:
parent
7765a3dcc2
commit
4faf102f9b
64
json-to-xlsx.js
Normal file
64
json-to-xlsx.js
Normal file
@ -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();
|
||||
Loading…
Reference in New Issue
Block a user