1

I'm trying to export some JSON data from my Angular to Excel. I already did it successfully. My problem is how would i include the headings to the excel also? I can only export the table but not the headings? Please see the link and codes below

CLICK HERE

CODE

public exportAsExcelFile(json: any[], excelFileName: string): void {

    const worksheet: XLSX.WorkSheet = XLSX.utils.json_to_sheet(json);
    console.log('worksheet',worksheet);
    const workbook: XLSX.WorkBook = { Sheets: { 'data': worksheet }, SheetNames: ['data'] };
    const excelBuffer: any = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
    //const excelBuffer: any = XLSX.write(workbook, { bookType: 'xlsx', type: 'buffer' });
    this.saveAsExcelFile(excelBuffer, excelFileName);
  }

  private saveAsExcelFile(buffer: any, fileName: string): void {
    const data: Blob = new Blob([buffer], {
      type: EXCEL_TYPE
    });
    FileSaver.saveAs(data, fileName + '_export_' + new Date().getTime() + EXCEL_EXTENSION);
  }

PIC

enter image description here

1 Answer 1

1

You need to add the following code once your have created your sheets

XLSX.utils.sheet_add_json(worksheet, [
    { A: '', B: '', C: ''},
], { header: ['A', 'B', 'C'], skipHeader: true, origin: -1 });
this.sheetHeaders(worksheet);

Updated stackblitz

Updated stackblitz 2

Sign up to request clarification or add additional context in comments.

5 Comments

It should create a row above the table headers. Yours is overriding the Eid, Ename, Esal @Siddhartha Gupta
Oops! Misinterpreted your question... Please look at update stackblitz
Thanks a lot but one more thing. I need to put value in headings like this for example Name: 'Joseph', Age: 10, Gender: 'Male'. Thank you
can you paste a sample excel example
This seems to be a completely different task from initial question. Still I've added a new stackblitz for you. In future post a new question... Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.