[英]How to dynamically populate an Excel file using exceljs in express?
Right now I have the following function:现在我有以下 function:
const generateXLSX = (res, data) => {
let baseFile = './src/utils/boop.xlsx';
let wb = new Excel.Workbook();
wb.xlsx.readFile(baseFile)
.then (async () => {
let ws = wb.getWorksheet(1);
let row = ws.getRow(9);
row.getCell(3).value = 'Simple and not so funny test';
row.commit();
res.header('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
await wb.xlsx.write(res);
res.end();
})
};
This will edit my base Excel document and produce this:这将编辑我的基本 Excel 文档并生成:
The problem here is that I want to populate this template using a JSON Object like the following:这里的问题是我想使用 JSON Object 填充此模板,如下所示:
"id": 1,
"urlImagen": "http://placeimg.com/640/480",
"name": "test national",
"pdu": "53014",
"creationDate": 2020,
"appevel": "ascending",
"ddlevel": "descending",
"mapa": 1,
"Module": "Lead",
"sector": "Something"
As you can see it contains data that i don't want to render into the Excel.如您所见,它包含我不想渲染到 Excel 的数据。 I want to implement a dynamic way to allocate the information without writing the same code like:
我想实现一种动态的方式来分配信息,而无需编写相同的代码,例如:
let row = ws.getRow(9);
row.getCell(3).value = 'Simple and not so funny test';
let row = ws.getRow(10);
row.getCell(3).value = 'Value 2';
let row = ws.getRow(11);
row.getCell(3).value = 'Value 3';
And so on, but I don't know how to implement an optimal way to solve this...等等,但我不知道如何实现解决这个问题的最佳方法......
you need to loop the data and write it into desired cells.您需要循环数据并将其写入所需的单元格。
try this尝试这个
const generateXLSX = async(res, data) => {
const baseFile = './src/utils/boop.xlsx';
const wb = new Excel.Workbook();
await wb.xlsx.readFile(baseFile);
const ws = wb.getWorksheet(1);
// loop and write data
for (let [rowNum, inputData] of data.entries()) {
console.log('row: ', rowNum, ', data', inputData);
// increment rowNum to change the row start position if needed
// for example, start at 5th row:
// let row = ws.getRow(rowNum+6);
let row = ws.getRow(rowNum + 1);
// insert values
row.getCell(1).value = inputData.pdu;
row.getCell(2).value = inputData.name;
row.getCell(3).value = inputData.appevel;
row.commit();
}
await wb.xlsx.writeFile(baseFile);
res.header('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
res.end();
};
// input data format
const data = [{
"id": 1,
"urlImagen": "http://placeimg.com/640/480",
"name": "test national",
"pdu": "53014",
"creationDate": 2020,
"appevel": "ascending",
"ddlevel": "descending",
"mapa": 1,
"Module": "Lead",
"sector": "Something"
}];
generateXLSX(res, data);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.