Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read and write a xlsm file using exceljs package npm

I have a xlsm file with few data already in it and need to write some data and create a new xlsm file during automation. With below code the file gets created , but it becomes corrupt and unable to open. File size reduces, for ex from 8kb to 7kb. Not sure what is getting missed while writing the file.

var Excel = require('exceljs');
var workbook = new Excel.Workbook();

workbook.xlsx.readFile('Book.xlsm')
.then(function () {
var worksheet = workbook.getWorksheet(1);
var row = worksheet.getRow(1);
console.log(row.getCell(1).value + " - First value"); // Get A1 value
row.getCell(3).value = "c"; //Set value to A3
row.commit();
return workbook.xlsx.writeFile('new.xlsm');
})

Note : Just created Book.xlsm with some value columns a,b and values 1,2. Trying to set A3 with 'c' and save as new.xlsm

If there are any other npm package which doesn't have this problem also would be great.

like image 802
Nalu Avatar asked Oct 18 '18 23:10

Nalu


People also ask

How do I download an Excel file from node js using ExcelJS?

var Excel = require('exceljs'); var workbook = new Excel. Workbook(); var worksheet = workbook. addWorksheet('My Sheet'); worksheet. columns = [ { header: 'Id', key: 'id', width: 10 }, { header: 'Name', key: 'name', width: 32 }, { header: 'D.O.B.

Does Openpyxl support XLSM?

Openpyxl is a Python library for reading and writing Excel (with extension xlsx/xlsm/xltx/xltm) files.

How do I open and edit XLSM files?

You can use XLSM files without Excel with free programs like OpenOffice Calc and WPS Office Spreadsheets. Another example of a free Office alternative that lets you edit and save back to this format is Microsoft Excel Online. Google Sheets is another way to open and edit an XLSM file online.


1 Answers

I think that currently exeljs is not suitable package for working with xlsm files. More robust package for this case is xlsx.

Here is a small code snippet that will demonstrate reading existing xlsm file, adding additional data to it and writing new xlsm file. You can test it in NodeJS environment.

Note that when working with xlsm files you pass bookVBA: true option to readFile method, which by default is false. See parsing options for details.

const XLSX = require('xlsx');

try {

    const workbook = XLSX.readFile('./test.xlsm', { bookVBA: true });
    let worksheet = workbook.Sheets['Sheet1'];
    XLSX.utils.sheet_add_aoa(worksheet, [
        ['text in A1', 'text in B1', 5000],
        ['text in A2', 'text in B2', 'text in C2'],
        [null, new Date(), 'text in C3', 'text in D3']
    ]);
    XLSX.writeFile(workbook, './output.xlsm');
    console.log('Completed ...');

} catch (error) {
    console.log(error.message);
    console.log(error.stack);
}

See the supported output formats for details.

like image 177
codtex Avatar answered Dec 24 '22 01:12

codtex