Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add rows before the column header using excel.js module + node

I am trying to create xslx file using excel.js module in node.js. I was able to create the columns and add its values. But, I need to insert some rows before the columns headers, where I can have some descriptions. How can I do that?

I need something like this

Any help will be appreciated

The code I tried is

     var worksheet = workbook.getWorksheet(1);
    worksheet.mergeCells('A1:B1');
    var row = worksheet.getRow(1);
    row.getCell(1).value =' Hello, World!'; 
   // ... merged cells are linked 
    worksheet.getCell('A1').value = 'PI';
    worksheet.columns = [
        {header: 'Id', key: 'id', width: 10},
        {header: 'Name', key: 'name', width: 32},
        {header: 'complexity', key: 'complexity', width: 10},
        {header: 'hours', key: 'hours', width: 10},
        {header: 'cost', key: 'cost', width: 10}
    ];
     worksheet.addRow({name:'m', complexity: 'd', hours:5, cost: 7});
like image 221
Mariya James Avatar asked Jun 15 '16 08:06

Mariya James


People also ask

How do I promote a row to a column header in Excel?

To promote the first row to column headers, select Home > Use First Row As Headers. To demote column headers to the first row, select Home, select the arrow next to Use First Row As Headers, and then select Use Headers as First Row.

What is the use of ExcelJS?

ExcelJS is a JavaScript library for reading, manipulating and writing spreadsheet data in XLSX format.


1 Answers

Found answer at https://github.com/guyonroche/exceljs/issues/433

> @rihabbs: I need to do like this example [![enter image description here][1]][1] [1]: https://i.stack.imgur.com/9oRE4.png

> @mfahmirukman:

/*TITLE*/
sheet.mergeCells('C1', 'J2');
sheet.getCell('C1').value = 'Client List'

/*Column headers*/
sheet.getRow(9).values = ['idClient', 'Name', 'Tel', 'Adresse'];

/*Define your column keys because this is what you use to insert your data according to your columns, they're column A, B, C, D respectively being idClient, Name, Tel, and Adresse.
So, it's pretty straight forward */
sheet.columns = [
  { key: 'idClient'},
  { key: 'name'},
  { key: 'tel'},
  { key: 'adresse'}
]

/*Let's say you stored your data in an array called arrData. Let's say that your arrData looks like this */
arrData = [{
  idClient: 1,
  name: 'Rihabbs',
  tel: '0123456789',
  adresse: 'Home sweet home'
},
{
  idClient: 2,
  name: 'mfahmirukman',
  tel: '0123456789',
  adresse: 'Indonesia'
}
]
/* Now we use the keys we defined earlier to insert your data by iterating through arrData and calling worksheet.addRow()
*/
arrData.forEach(function(item, index) {
  sheet.addRow({
     idClient: item.idClient,
     name: item.name,
     tel: item.tel,
     adresse: item.adresse
  })
})
like image 58
dim Avatar answered Sep 20 '22 12:09

dim