简体   繁体   中英

How can I write xlsx to file in browser with ExcelJS?

I am trying to create an xlsx file in the browser and find https://github.com/exceljs/exceljs very powerful. However, I can't find a way how to save my xlsx object to a file. Probably I need to use Buffer, but how to generate a file from it?

const buffer = await workbook.xlsx.writeBuffer();

This library can generate files in the browser https://docs.sheetjs.com/docs/ but it is not good at building complex fields.

Use FileSaver.js ( https://github.com/eligrey/FileSaver.js/ )

var FileSaver = require('file-saver');
const buffer = await workbook.xlsx.writeBuffer();
FileSaver.saveAs(new Blob([buffer]), “result.xlsx”);

You can do it without FileSaver.js.

Creating a buffer for ExcelJS:

let buffer = await workbook.xlsx.writeBuffer();

Creating a buffer for SheetJS:

let buffer = XLSX.write(workBook, { bookType: 'xlsx', compression: true, type: 'buffer' });

Saving to a file for both libraries:

        let blob = new Blob([buffer], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" });
        let link = document.createElement('a');
        link.href = URL.createObjectURL(blob);
        link.download = "fName.xlsx";
        link.click();
        URL.revokeObjectURL(link.href);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM