node.jsxlsxsheetjs

Stream SheetJS xlsx to form-data in node


I need to generate and upload a xlsx in node. Any way to do this without saving the file to disk?

import FormData from 'form-data';
import XLSX from 'xlsx';
import * as fs from 'fs';

var form = new FormData();
var data = [['a','b'],[1,2]];
var ws = XLSX.utils.aoa_to_sheet(data);
let wb = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(wb, ws, "Sheet1");

//can I combine the next 2 lines somehow?
XLSX.writeFile(wb, 'abc.xlsx', {compression:true});
form.append('file', fs.createReadStream('abc.xlsx'));
//...

Solution

  • Just write the workbook as a buffer (by passing buffer type to write, see write output types), and then simply append it to form-data:

    const file = XLSX.write(wb, {type: 'buffer', compression:true});
    
    form.append('file', file, {filename: 'abc.xlsx'});