Search code examples
excelnode.jsfile-ioexport-to-excelnpm

How to create an Excel File with Nodejs?


I am a nodejs programmer . Now I have a table of data that I want to save in Excel File format . How do I go about doing this ?

I found a few Node libraries . But most of them are Excel Parsers rather than Excel Writers .I am using a Linux Server . Hence need something that can run on Linux . Please let me know if there are any helpful libraries that you know of .

Or is there a way I can convert a CSV file to an xls file ( programmatically ) ?


Solution

  • Update 2024: You may wish to check @defraggled's answer below, as xlsx aka 'SheetJS' now has more downloads than excel4node

    excel4node is a maintained, native Excel file creator built from the official specification. It's similar to, but more maintained than msexcel-builder mentioned in the other answer.

    // Require library
    var excel = require('excel4node');
    
    // Create a new instance of a Workbook class
    var workbook = new excel.Workbook();
    
    // Add Worksheets to the workbook
    var worksheet = workbook.addWorksheet('Sheet 1');
    var worksheet2 = workbook.addWorksheet('Sheet 2');
    
    // Create a reusable style
    var style = workbook.createStyle({
      font: {
        color: '#FF0800',
        size: 12
      },
      numberFormat: '$#,##0.00; ($#,##0.00); -'
    });
    
    // Set value of cell A1 to 100 as a number type styled with paramaters of style
    worksheet.cell(1,1).number(100).style(style);
    
    // Set value of cell B1 to 300 as a number type styled with paramaters of style
    worksheet.cell(1,2).number(200).style(style);
    
    // Set value of cell C1 to a formula styled with paramaters of style
    worksheet.cell(1,3).formula('A1 + B1').style(style);
    
    // Set value of cell A2 to 'string' styled with paramaters of style
    worksheet.cell(2,1).string('string').style(style);
    
    // Set value of cell A3 to true as a boolean type styled with paramaters of style but with an adjustment to the font size.
    worksheet.cell(3,1).bool(true).style(style).style({font: {size: 14}});
    
    workbook.write('Excel.xlsx');