Search code examples
javascriptxlsxfile-saver

Why is 'xlsx' used with 'file-saver' to download excel?


I know that 'xlsx' can download excel such as:

xlsx.writeFile(book, "saveXlsx.xlsx");

but some examples, they used 'file-saver' to download excel

such as:

function exportExcel(){ 
// step 1. create workbook
var wb = XLSX.utils.book_new();

// step 2. create sheet 
var newWorksheet = excelHandler.getWorksheet();

// step 3. append sheet to workbook
XLSX.utils.book_append_sheet(wb, newWorksheet, excelHandler.getSheetName());

// step 4. create excel file
var wbout = XLSX.write(wb, {bookType:'xlsx',  type: 'binary'});

// step 5. save excel file used file-saver
saveAs(new Blob([s2ab(wbout)],{type:"application/octet-stream"}), excelHandler.getExcelFileName());

var excelHandler = {
    getExcelFileName : function(){
        return 'table-test.xlsx';
    },
    getSheetName : function(){
        return 'Table Test Sheet';
    },
    getExcelData : function(){
        return document.getElementById('tableData'); 
    },
    getWorksheet : function(){
        return XLSX.utils.table_to_sheet(this.getExcelData());
    }

} }

why they do that?

I think that step 5 isn't nessasary, it can replace to this:

xlsx.writeFile(book, "saveXlsx.xlsx");

Solution

  • It's the same in most browsers as the information of Download a file in legacy browsers in Readme https://www.npmjs.com/package/xlsx/v/0.18.5

    XLSX.writeFile techniques work for most modern browsers as well as older IE. For much older browsers, there are workarounds implemented by wrapper libraries.

    FileSaver.js implements saveAs. Note: XLSX.writeFile will automatically call saveAs if available.

    I guess it depends on your xlsx library version.Maybe saveAs works well in some much older browsers while xlsx.writeFile doesn't.