Skip to content
Advertisement

How to save excel workbook using Javascript

I have created an HTML form that takes in user data and using exceljs and a few other libraries I store this data into an excel spreadsheet. This part of my code works perfectly fine. However, when I refresh the server, the data stored in the excel file previously gets deleted.

I believe the reason is that I could not save the excel workbook….but when I searched up for some code to achieve this and executed it…the code didn’t work.

Here is the code that collects user data into the excel worksheet:

JavaScript

Advertisement

Answer

Your code is working fine. The issue is, each time your server is restarted, you are recreating a new excel file with same name.

You have to implement some extra logic to check if the file already exists in the server. If so, then don’t create the file, just append the new row to the existing file otherwise create a new file and save the data.

I have added below working example:

JavaScript

Notes (extra):

  • Your row is actually appened when you’re doing worksheet.addRows(info);

  • use a try/catch before checking the with fs.

  • In the docs, it’s mentioned that writing to a xlsx file is asynchronous hence await should be used. So use async/await to log the result after safely saving file.

JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement