angulartypescriptexport-to-excelsheetjs

How to add warning text before object array while exporting to excel in angular


I have an array of objects coming from api, before I print it to excel, I want to merge multiple cells at the top of the sheet, and insert a warning message into them. something like this

I wanted to write something like the following code. But it didn't work. Is it possible to do that with XLSX?

this.excelData.unshift("warning message");
var ws = XLSX.utils.json_to_sheet((this.excelData as any));

Solution

  • Here is one way to do it:

    // Put warning message in A1
    // aoa stands for 'array of arrays'
    const ws = XLSX.utils.aoa_to_sheet([['WARNING']]);
    
    // Merge A1 to L2
    // Property names: s: start, e: end, c: column, r: row
    ws['!merges'] = [{s: {c: 0, r: 0}, e: {c: 11, r: 1}}];
    
    // Append data starting at A3
    XLSX.utils.sheet_add_json(ws, this.excelData, {origin: 'A3'});