| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394 |
- import ExcelJS from "exceljs";
- import * as fs from "node:fs";
- import * as path from "node:path";
- // 创建工作簿和工作表
- const workbook = new ExcelJS.Workbook();
- /**
- * 想workbook添加worksheet
- * @param name 区域名
- * @param data 区域物资数据
- */
- function addWorkSheet(name, data) {
- const worksheet = workbook.addWorksheet(name);
- // 确保 Excel 中显示网格线
- worksheet.views = [{ showGridLines: true }];
- // 解析数据并逐行写入
- data.forEach(row => worksheet.addRow(row));
- //设置表头样式(深蓝底色、白字、加粗、居中)
- const headerRow = worksheet.getRow(1);
- headerRow.height = 28;
- headerRow.eachCell((cell) => {
- cell.border = {
- top: { style: "thin", color: { argb: "333333" } },
- left: { style: "thin", color: { argb: "333333" } },
- bottom: { style: "thin", color: { argb: "333333" } },
- right: { style: "thin", color: { argb: "333333" } }
- };
- cell.font = {
- name: "微软雅黑",
- size: 12,
- bold: true,
- color: { argb: "000000" }
- };
- cell.alignment = {
- horizontal: "center",
- vertical: "middle"
- };
- });
- // 设置数据行样式(细边框、对齐方式、行高)
- worksheet.eachRow((row, rowNumber) => {
- if(rowNumber > 1) {
- row.height = 20;
- row.eachCell((cell, colNumber) => {
- cell.font = {
- name: "微软雅黑",
- size: 12,
- color: { argb: "000000" }
- };
- cell.border = {
- top: { style: "thin", color: { argb: "333333" } },
- left: { style: "thin", color: { argb: "333333" } },
- bottom: { style: "thin", color: { argb: "333333" } },
- right: { style: "thin", color: { argb: "333333" } }
- };
- cell.alignment = {
- horizontal: [6, 7].includes(colNumber) ? "center" : "left",
- vertical: "middle"
- };
- });
- }
- });
- //自动根据内容调整列宽
- worksheet.columns.forEach(column => {
- let maxLength = 0;
- column.eachCell({ includeEmpty: true }, cell => {
- const columnLength = cell.value ? cell.value.toString().length : 0;
- if(columnLength > maxLength) {
- maxLength = columnLength;
- }
- });
- column.width = Math.max(maxLength + 4, 20);
- });
- }
- // 读取数据转成worksheet并添加到workbook
- const pathDataOrigin = "data-origin";
- const filenames = fs.readdirSync(path.resolve(pathDataOrigin));
- for (let i = 0; i < filenames.length; i++) {
- const filename = filenames[i];
- if(!filename.endsWith(".json")) continue;
- const textDataOrigin = fs.readFileSync(path.resolve(pathDataOrigin, filename)).toString();
- const areaGlobal = filename.replace("-物资表.json", "");
- const dataOrigin = JSON.parse(textDataOrigin);
- addWorkSheet(areaGlobal, dataOrigin);
- }
- // 保存文件
- await workbook.xlsx.writeFile(path.resolve("data-output/物资表.xlsx"));
|