Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting new row / note at the beginning of a sheet during XLSX Export

Tags:

node.js

xlsx

I am new to node.js and I am able to write my data into workbook but I am facing an issue with inserting a note at the beginning of my data. Please note that the data is being fetched from DB but note is static or from session.

var export = XLSX.utils.json_to_sheet(this.obj);
    var wb = XLSX.utils.book_new() // make Workbook of Excel
    // add Worksheet to Workbook    
    XLSX.utils.book_append_sheet(wb, export, 'sheet1') // sheet1 is name of Worksheet  
    XLSX.utils.sheet_add_json(wb.Sheets.sheet1,
      [
        {note: "This is a note"},
      ],
      {
        header: ["note"],
        skipHeader:true,
        origin: "A1"
      }
    );
    // export Excel file
    XLSX.writeFile(wb, 'book.csv') // name of the file is 'book.xlsx'

here in the above code I am trying to add note using sheet_add_json but it is overwriting the existing data at A1. Though it works fine when tried with empty cell

Below is expected output in excel format.

This is a Note

Name    RollNo  Age
Abc      101    10
def      102    15
xyz      103    20

But As per the current code I am getting

This is a Note  RollNo  Age
Abc              101    10
def              102    15
xyz              103    20
like image 758
Tia Avatar asked Dec 08 '25 10:12

Tia


1 Answers

from the documentation "XLSX.utils.sheet_add_json takes an array of objects and updates an existing worksheet object. It follows the same process as json_to_sheet and accepts an options argument:" It will only update, or it can add as new row at the bottom, using origin: -1.

try this:

//create sheet with empty json/there might be other ways to do this
export = XLSX.utils.json_to_sheet({});

//start frm A2 here 
XLSX.utils.sheet_add_json(wb.Sheets.sheet1,
  [{
    Name: 'Abc',
    RollNo: 101,
    Age: 10
   },
   {
    Name: 'def',
    RollNo: 102,
    Age: 15
   },
   {
    Name: 'xyz',
    RollNo: 103,
    Age: 20
   }],
  {
    header: ["note"],
    skipHeader:true,
    origin: "A2"
  }
);

//then add ur txt
 XLSX.utils.sheet_add_json(wb.Sheets.sheet1,
  [
    {note: "This is a note"},
  ],
  {
    header: ["note"],
    skipHeader:true,
    origin: "A1"
  }
);
like image 131
3960278 Avatar answered Dec 10 '25 00:12

3960278



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!