0

I am using exceljs 3.8 to create new xlsx file but some reason below code not working ?

     createNewExcelFile:  function (excelFilePath) {
           //excelFilePath: Provide path and file name for excel file
           // load exceljs module
           var workbook = new exceljs.Workbook(); //create object of workbook
           //add sheet to workbook
           var newSheet = workbook.addWorksheet('TestData');
           //use write file function to create new file
           workbook.xlsx.writeBuffer(excelFilePath) 
               .then(function () {
                   console.log("excel file created successfully");
               });
       }

createNewExcelFile('new1.xlsx');

console.log is logging "excel file created successfully" but i don't see any where file getting created.

jsduniya
  • 2,464
  • 7
  • 30
  • 45

1 Answers1

2

1. You should use writeFile instead of writeBuffer

workbook.xlsx.writeFile(excelFilePath);

(Source: https://github.com/exceljs/exceljs#writing-xlsx)

2. xlsx-renderer

I would also recommend using xlsx-renderer which provides generating excel files based on Template and ViewModel.

Template + ViewModel = Preaty XLSX

Template: Template file

VM:

{
"projects": [
    {
        "name": "ExcelJS",
        "role": "maintainer",
        "platform": "github",
        "link": "https://github.com/exceljs/exceljs",
        "stars": 5300,
        "forks": 682
    },
    {
        "name": "xlsx-import",
        "role": "owner",
        "platform": "github",
        "link": "https://github.com/siemienik/xlsx-import",
...

Gives: enter image description here

This library will work great with your code because it based on ExcelJs too.

(Source: https://github.com/Siemienik/xlsx-renderer/tree/master/tests/integration/data/Renderer009-ForEach-Average)

EDIT: (29.04.2020) In the practice it's used by the following code:

const result = await renderer.renderFromFile('./report-template.xlsx', { awesome:"Oh yeah!", items:[/*...*/]});
await result.xlsx.writeFile('./my-awesome-report.xlsx');
  • So you mean this library automatically create file and add data into it..no need to create any empty excel also ? – jsduniya Apr 29 '20 at 03:11
  • 1
    Yeah, it uses the template that was prepared before. And put data into a cell with value started by `##`. It has the possibility to looping / inserting hyperlinks and many more. It's really fine because allow easily change the template without any code changes. For example, always when a company change visual identification. I've added also into the post above code how to use it. It's will be available as a restful microservice under docker soon. – Paweł Siemienik Apr 29 '20 at 17:24