0

我想将一组对象解析为 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');
4

1 回答 1

1

它也适用于使用或使用单个单元格的 Arrays 或 Arrays( [[..][..]]) 。range

文档

xlsx-populate 还支持单元格范围,以允许一次解析/操作多个单元格。

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' ] ]
于 2019-11-29T15:08:11.380 回答