while using header option with XLSX.utils.json_to_sheet , headers not overriding

LearningPal picture LearningPal · Apr 23, 2019 · Viewed 14.4k times · Source

While I try to change header titles by passing array of titles to options like below it does not override the headers. Instead it writes new headers first and original data with old headers again from next cell. I am passing the same numbers of header titles.

Here is my code

const ws: XLSX.WorkSheet = XLSX.utils.json_to_sheet(json, {header: headerColumns});
    const wb: XLSX.WorkBook = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, 'Transactions');
    const excelBuffer: any = XLSX.write(wb, { bookType: 'xlsx', type: 'array' });
    this.saveAsExcelFile(excelBuffer, excelFileName);

And output looks like below.

enter image description here

Answer

Prabhanath picture Prabhanath · Sep 17, 2019

The basic job of "header" option is not to override, rather just shift the starting option of the columns. i.e. any value passed in the header option will be treated as the first column, provided the value should match with existing keys you have in the data.

XLSX.utils.json_to_sheet([{A:1,B:2},{B:2,C:3}], {header:['C']})

Here column "C" will be the first column in the excel. For more look out for detailed description here : https://docs.sheetjs.com/#sheetjs-js-xlsx