本文主要是介绍如何利用exceljs将data数据导出表格实现日期去重,同时保留对应日期的每一列数据,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
const data = [{ deviceId: 1, name: "B相电压", signalTypeId: 1, ts: "2024-05-13 12:10:06", unit: "kV", 1: 39.37936, value:39.37936, },{ deviceId: 1, name: "A相电压", signalTypeId: 2, ts: "2024-05-13 12:11:06", unit: "kV", 1: 39.37936, value:39.37936, },{ deviceId: 1, name: "A相电压", signalTypeId: 2, ts: "2024-05-13 12:11:06", unit: "kV", 2: 39.37936, value:39.37936, },{ deviceId: 1, name: "A相电压", signalTypeId: 3, ts: "2024-05-13 12:12:06", unit: "kV", 3: 39.37936, value:39.37936, },] sheet1.columns = [ { header: '日期', key: 'ts', width: 10 }, { header: "A相", key: '1', width: 32 }, { header: 'B相', key: '2', width: 10 }, { header: 'B相', key: '3', width: 10 } ];
columns中的key值是data对象中的1:39.37936中的key,如何利用exceljs将data数据导出表格实现日期去重,同时保留对应日期的每一列数据
为了实现日期去重并保留对应日期的每一列数据,你可以使用一个对象来存储每个日期的数据,然后将该对象中的数据填充到工作表中。以下是修改后的示例代码:
const ExcelJS = require('exceljs');// 示例数据
const data = [{deviceId: 1,name: "B相电压",signalTypeId: 1,ts: "2024-05-13 12:10:06",unit: "kV",1: 39.37936,value: 39.37936,
}, {deviceId: 1,name: "A相电压",signalTypeId: 2,ts: "2024-05-13 12:11:06",unit: "kV",1: 39.37936,value: 39.37936,
}, {deviceId: 1,name: "A相电压",signalTypeId: 2,ts: "2024-05-13 12:11:06",unit: "kV",2: 39.37936,value: 39.37936,
}, {deviceId: 1,name: "A相电压",signalTypeId: 3,ts: "2024-05-13 12:12:06",unit: "kV",3: 39.37936,value: 39.37936,
}];// 创建一个工作簿
const workbook = new ExcelJS.Workbook();// 添加一个工作表
const sheet1 = workbook.addWorksheet('Sheet1');// 设置列
sheet1.columns = [{ header: '日期', key: 'ts', width: 15 },{ header: "A相", key: '1', width: 15 },{ header: 'B相', key: '2', width: 15 },{ header: 'C相', key: '3', width: 15 }
];// 使用对象存储每个日期的数据
const rowDataMap = {};data.forEach(rowData => {const ts = rowData.ts;if (!rowDataMap[ts]) {rowDataMap[ts] = { ts };}const columnKey = rowData.signalTypeId.toString();rowDataMap[ts][columnKey] = rowData[columnKey] || '';
});// 填充数据
Object.values(rowDataMap).forEach(rowData => {sheet1.addRow(rowData);
});// 保存工作簿到文件
workbook.xlsx.writeFile('data.xlsx').then(() => {console.log('Excel 文件已生成');}).catch(err => {console.error('保存 Excel 文件时出错:', err);});
这篇关于如何利用exceljs将data数据导出表格实现日期去重,同时保留对应日期的每一列数据的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!