在Node.js/javascript中的Excel中创建动态列数或标头数 [英] Creating dynamic number of columns or header in excel in nodejs/javascript
问题描述
我已经在nodejs中使用 exceljs
模块将json数据导出到excel.一切正常,但是在添加行(即固定列)之前,必须先定义标题/列的名称.添加行后,我无法动态添加列.我已经尝试了通过npm可用的许多模块,但是它们都具有相同的功能.
I have used exceljs
module in nodejs for exporting json data to excel. It's working fine, but the names of headers/columns have to be predefined before adding rows i.e., columns are fixed. After addition of rows, I can't add columns dynamically.
I have tried a number of modules available through npm but all of them have the same features.
因此,在处理json数据时,是否有任何方法或模块可以创建新列并添加所需的行.
So, is there any way or module that, at the time of manipulation of json data, can create a new column and add the required row.
推荐答案
我尝试将新列直接推送到 worksheet.columns
,但是它不起作用.我做了一个变通办法,对我来说很好.
I tried directly pushing the new columns to the worksheet.columns
but it is not working. I did a workaround and working well for me.
注意:您需要跟踪工作表中已添加的列,才能按列索引获取下一个空列.
Note: You need to make the track of already added columns in the worksheet to get the next empty columns by column index.
这里是一个例子:
let workbook = new excel.Workbook(); //creating workbook
let worksheet = workbook.addWorksheet('Records'); //creating worksheet
const columns = [];
columns.push({header: 'Id', key: '_id', width: 30});
columns.push({header: 'Name', key: 'name', width: 30});
//Set Headers to WorkSheet Header
worksheet.columns = columns;
//Now insert some records if you want
worksheet.addRow({_id: "1", name: "Mitchell Starc"});
worksheet.addRow({_id: "2", name: "Ab de Villiers"});
//Update or add dynamic columns
//Get the empty columns from worksheet. You can get the empty columns number by using `columns` array length
//For this you have to track all inserted columns in worksheet
//This will return the next empty columns
let newColumn = worksheet.getColumn(columns.length + 1);
//Set new key header and all other required properties
newColumn.key = "profession";
newColumn.header = "Profession";
newColumn.width = 30;
//Add the new column to `columns` to track the added headers
columns.push(newColumn);
//Now you can insert rows with new columns
worksheet.addRow({_id: "3", name: "MS Dhoni", profession: "Cricket"});
workbook.xlsx.writeFile("records.xlsx")
.then(function () {
console.log("file saved!");
});
这篇关于在Node.js/javascript中的Excel中创建动态列数或标头数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!