XLSX can't save file

182 Views Asked by At

I have a function that reads in a workbook, adds some data, and then needs to write the file. I am able to read and add fine, but I get an error when I try any method of saving.

Here is my code:

import * as XLSX from 'xlsx/xlsx.mjs';
import * as fs from 'fs';
const xlsxFilePath = 'file.xlsx'

export function addReportToExcel(start, ID, viewID, title, description, attachements, submissionDate) {
    const workbook = XLSX.read(fs.readFileSync(xlsxFilePath));
    const worksheet = workbook.Sheets['Bugs'];
    const rowNumber = ID + 3; //accounts for headers taking up rows
    XLSX.utils.sheet_add_aoa(worksheet, [
            [viewID],
            [title],
            [description],
            [attachements],
            [submissionDate],
            ['Reviewing'],
            [submissionDate],
            ['-'],
            ['-']
        ], { origin: {c: start, r: rowNumber}});

            XLSX.writeFile(workbook, xlsxFilePath);
};

The error:

/node_modules/xlsx/xlsx.mjs:3220
        throw new Error("cannot save file " + fname);
              ^

Error: cannot save file book.xlsx
    at write_dl (/node_modules/xlsx/xlsx.mjs:3220:8)
    at write_zip_denouement (/node_modules/xlsx/xlsx.mjs:23898:31)
    at write_zip_type (/node_modules/xlsx/xlsx.mjs:23868:9)
    at writeSync (/node_modules/xlsx/xlsx.mjs:24005:22)
    at Module.writeFileSync (/node_modules/xlsx/xlsx.mjs:24028:9)
    at addReportToExcel (/src/common.js:60:14)
    at test.js:3:1
    at ModuleJob.run (node:internal/modules/esm/module_job:194:25)book.xlsx
1

There are 1 best solutions below

0
On

when using es modules you must load fs module to read and write file support.

import * as fs from 'fs';
// Set internal fs instance
XLSX.set_fs(fs);

accordion to this issue : issue

import * as XLSX from 'xlsx'
import * as fs from 'fs';
XLSX.set_fs(fs);

// -------------------------------------------

const data = [
  { name: "Alice", age: 25, gender: "F" },
  { name: "Bob", age: 30, gender: "M" },
  { name: "Charlie", age: 35, gender: "M" },
];

const wb = XLSX.utils.book_new();

const ws = XLSX.utils.json_to_sheet(data);

XLSX.utils.book_append_sheet(wb, ws, "Sheet1");

XLSX.writeFile(wb, "sample_file.xlsx");