I have an array of objects. By default, sheet_to_json uses object keys as headers. However, I need to rename those headers without explicitly modifying my array of objects.
Is this possible?
I'm sharing the solution that I found
// Using same variables as the above answer
var Heading = [
["FirstName", "Last Name", "Email"],
];
var Data = [
{firstName:"Jack", lastName: "Sparrow", email: "[email protected]"},
{firstName:"Harry", lastName: "Potter", email: "[email protected]"},
];
//Had to create a new workbook and then add the header
const ws = XLSX.utils.book_new();
XLSX.utils.sheet_add_aoa(ws, Heading);
//Starting in the second row to avoid overriding and skipping headers
XLSX.utils.sheet_add_json(ws, Data, { origin: 'A2', skipHeader: true });
This code is based on Angel Alvarez's answer and added a working demo:
let arr = [
{ firstName: 'Jack', lastName: 'Sparrow', email: '[email protected]' },
{ firstName: 'Harry', lastName: 'Potter', email: '[email protected]' },
];
let Heading = [['FirstName', 'Last Name', 'Email']];
//Had to create a new workbook and then add the header
const wb = XLSX.utils.book_new();
const ws: XLSX.WorkSheet = XLSX.utils.json_to_sheet([]);
XLSX.utils.sheet_add_aoa(ws, Heading);
//Starting in the second row to avoid overriding and skipping headers
XLSX.utils.sheet_add_json(ws, arr, { origin: 'A2', skipHeader: true });
XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');
XLSX.writeFile(wb, 'filename.xlsx');
STACKBLITZ DEMO
replace the last line with below.
XLSX.utils.sheet_add_json(ws, data, {skipHeader: true, origin: "A2"});
i made this work around because both of the above approach were not working for me
let EXCEL_EXTENSION = '.xlsx';
let worksheet: XLSX.WorkSheet;
let customHeader = true;
let sheetName = 'My Sheet 1';
if (customHeader) {
const headers: any = { Cust: 'Customer Name', Addr1: 'Address 1' };
this.data.unshift(headers); // if custom header, then make sure first row of data is custom header
worksheet = XLSX.utils.json_to_sheet(json, { skipHeader: true });
} else {
worksheet = XLSX.utils.json_to_sheet(json);
}
const workbook = XLSX.utils.book_new();
const fileName = 'myExcelFile_Export_' + moment().format('MM-DD-YYYY_hh:mm:ss').toString() + EXCEL_EXTENSION;
XLSX.utils.book_append_sheet(workbook, worksheet, sheetName);
XLSX.writeFile(workbook, fileName);
This works for me:
var wb = XLSX.utils.book_new();
var ws = XLSX.utils.json_to_sheet(json_data, { origin: 'A2', skipHeader: true });
XLSX.utils.sheet_add_aoa(ws, headings); //heading: array of arrays
XLSX.utils.book_append_sheet(wb, ws);
XLSX.writeFile(wb, filename + '.xlsx')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With