sheetjs icon indicating copy to clipboard operation
sheetjs copied to clipboard

How to add headers manually to the sheet before exporting

Open Vinutha-BK opened this issue 7 years ago • 5 comments

Hi ,

This is good option. I am using in my project . Currently headers are same as the list fields. data = [{name:'Albert', userid:'[email protected]'},{name:'Robert', userid:'[email protected]'}] I want to have header names like 'Name' and 'User Id' I am not getting how to pass headers manually.

function exportJsonToFile(data, fileType: any, name: string) { const worksheet: XLSX.WorkSheet = XLSX.utils.json_to_sheet(data); const workbook: XLSX.WorkBook = { Sheets: { data: worksheet }, SheetNames: ['data'] }; const excelBuffer: any = XLSX.write(workbook, { bookType: fileType, type: 'array' }); const blob: Blob = new Blob([excelBuffer], { type: '.' + fileType }); FileSaver.saveAs(blob, name + '.' + fileType); }

Vinutha-BK avatar Feb 27 '19 02:02 Vinutha-BK

Dont know about about json_to_sheet but you can do that easily with aoa_to_sheet(which is array of arrays) as input. If you can make your response like arrayOfArrays = [[Name, userId], [Albert, '[email protected]], [Robert, '[email protected]']] and then save it to sheet with xlsx.utils.aoa_to_sheet(arrayOfArrays).

phani17c avatar Feb 27 '19 21:02 phani17c

@phani17c , I can have upto 24k data in json format , converting to array of arrays will hit performance

Vinutha-BK avatar Mar 08 '19 01:03 Vinutha-BK

Write as normal, then go back and re-write the first row. You can use sheet_add_aoa with origin:0 to write to the first row of the worksheet

reviewher avatar Sep 15 '21 06:09 reviewher

if you use react , you could use this code to change header names to your choices , hope that helps someone

data.map(function(rendezvous:any) { return {Début:rendezvous.start, Fin:rendezvous.end , Titre : rendezvous.title , Patient : rendezvous.cin + '::' + rendezvous.namePatient}; }))

of course you should use it before you export your excel file

khayyak avatar Jun 03 '22 10:06 khayyak

Write as normal, then go back and re-write the first row. You can use sheet_add_aoa with origin:0 to write to the first row of the worksheet

it gonna be override the first row. So the way I found that I write the header first then add sheet_add_aoa with origin:1 with the data. Like this:

const header = [['Your header']];
const ws: xlsx.WorkSheet = xlsx.utils.aoa_to_sheet(header);
xlsx.utils.sheet_add_aoa(ws, data, {origin:1});

hvtung avatar May 22 '23 04:05 hvtung