js-xlsx

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


I'm trying to change header titles by passing an array of titles to options but it does not override the headers. Instead it inserts new headers before the original data. 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


Solution

  • The basic job of the "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