'while using header option with XLSX.utils.json_to_sheet , headers not overriding
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.
Solution 1:[1]
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
Solution 2:[2]
This is how I have achieved similar behavior.
const XLSX = require('xlsx');
const wb = XLSX.utils.book_new();
const Heading = [
['Sr No', 'User Name', 'Department', 'Bank', 'Country', 'Region', 'Amount']
];
// creating sheet and adding data from 2nd row of column A.
// Leaving first row to add Heading
const ws = XLSX.utils.json_to_sheet(data, { origin: 'A2', skipHeader: true });
// adding heading to the first row of the created sheet.
// sheet already have contents from above statement.
XLSX.utils.sheet_add_aoa(ws, Heading, { origin: 'A1' });
// appending sheet with a name
XLSX.utils.book_append_sheet(wb, ws, 'Records');
const fileContent = XLSX.write(wb, { bookType: 'xlsx', type: 'buffer' });
Solution 3:[3]
very traditional approach but working, please see complete code below :
const worksheet: XLSX.WorkSheet = XLSX.utils.json_to_sheet(this.releaseDateWiseCountList);
worksheet.A1.v = "Pick Release Date";
worksheet.B1.v = "Task Type";
worksheet.C1.v = "First Shift";
worksheet.D1.v = "Second Shift";
worksheet.E1.v = "Total";
worksheet.F1.v = "Grand Total";
worksheet.G1.v = "Pick %";
const workbook: XLSX.WorkBook = { Sheets: { 'data': worksheet }, SheetNames: ['data'] };
const excelBuffer: any = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
const data: Blob = new Blob([buffer], {type: EXCEL_TYPE});
FileSaver.saveAs(data , 'Result_export_' + new Date().getTime() + EXCEL_EXTENSION);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | frogatto |
Solution 2 | Jacob Nelson |
Solution 3 | Mopendra Kumar |