Exceljs: Excel file gets saved without the .xlsx suffix

Created on 12 Aug 2017  路  2Comments  路  Source: exceljs/exceljs

This is my excel code:

var Excel = require('exceljs');
var tempfile = require('tempfile');

router.get('/download/excel', function(req, res) {
try {
        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.', key: 'DOB', width: 10 }
        ];
        worksheet.addRow({id: 1, name: 'John Doe', dob: new Date(1970,1,1)});
        worksheet.addRow({id: 2, name: 'Jane Doe', dob: new Date(1965,1,7)});

        var tempFilePath = tempfile('.xlsx');
        workbook.xlsx.writeFile(tempFilePath).then(function() {
            console.log('file is written');
            res.sendFile(tempFilePath, function(err){
                console.log('---------- error downloading file: ' + err);
            });
        });
    } catch(err) {
        console.log('OOOOOOO this is the error: ' + err);
    }
});

The excel file is created and saved to my downloads folder but it does not show it as an excel file.

The name of the file is "excel" and there is no .xlsx suffix at the end. This results in the OS not recognizing the file type and when I double click and open it, it opens as a TextEdit (I am using Mac).

What can be done to prevent this? Also, how do I name the file (in the code) before downloading it?

Thanks.

Most helpful comment

@brendanbur, thanks a ton, that worked.

All 2 comments

When I ran into this issue, I was writing the workbook directly to the response object instead of a temp file, but the solution I found was to set response headers like this:

res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
res.setHeader('Content-Disposition', 'attachment; filename=FILENAME.xlsx');
workbook.xlsx.write(res).then(function() {
   res.end();
});

@brendanbur, thanks a ton, that worked.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

CountryGuide picture CountryGuide  路  3Comments

lukelaws picture lukelaws  路  3Comments

thearabbit picture thearabbit  路  3Comments

ljkmchale picture ljkmchale  路  4Comments

Toub picture Toub  路  3Comments