0

I want to parse an array of objects into xlsx-populate so it can give me the excel file.

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');

1 Answers1

1

It works for Arrays or Arrays([[..][..]]) using range or using single cell as well.

From the doc:

xlsx-populate also supports ranges of cells to allow parsing/manipulation of multiple cells at once.

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());

Alternatively, you can set the values in a range with only the top-left cell in the range:

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

So all you need to do is converting objects to CSV maybe for an example JS object:

Modified(only removed the .joins) From this answer:

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' ] ]
Aritra Chakraborty
  • 12,123
  • 3
  • 26
  • 35