我可以使用 xlsx-populate 解析为'json/[对象]吗?



我想将对象数组解析为 xlsx-populate,以便它可以给我 excel 文件。

const xlsxPopulate = require('xlsx-populate');
const worksheet = await xlsxPopulate.fromBlankAsync();
const sheet1 = worksheet.sheet('Sheet1');
sheet1.cell('A1').value(newArray);
await worksheet.toFileAsync('./myFileName.xlsx');

它适用于使用range或使用单个单元格的数组或数组([[..][..]](。

从文档中:

XLSX 填充还支持允许的单元格范围 一次解析/操作多个单元格。

const r = workbook.sheet(0).range("A1:C3");
// Set all cell values to the same value:
r.value(5);
// Set the values using a 2D array:
r.value([
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]);
// Set the values using a callback function:
r.value((cell, ri, ci, range) => Math.random());

或者,您可以在仅使用 区域中左上角的单元格:

workbook.sheet(0).cell("A1").value([
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]);

所以你需要做的就是将对象转换为CSV,也许是一个示例JS对象:

修改(仅删除了.joins(从这个答案:

const json = [
{
h1:1,
h2:2
},
{
h1:3,
h2:4
}
];
var fields = Object.keys(json[0])
var replacer = function(key, value) { return value === null ? '' : value } 
var csv = json.map(function(row){
return fields.map(function(fieldName){
return JSON.stringify(row[fieldName], replacer)
})
})
csv.unshift(fields) // add header column
console.log(csv) //[ [ 'h1', 'h2' ], [ '1', '2' ], [ '3', '4' ] ]

最新更新