0

I am creating an xlsx workbook using the module exceljs and then I would like to send it as an attachment through my express middleware.

I create and save my workbook in a stream using the following code as shown in documentation of the module

    var stream = fs.createWriteStream('test.xlsx');    
    // write to a stream
    workbook.xlsx.write(stream)
        .then(function() {
            // done
    }); 

where stream is a writable stream.

My problem is that I can't understand how to handle the stream in order to send it. Trying to pipe it to res stream.pipe(res) gives my an error that is not readable stream to pipe it.

What is the best course of action for me now?

p.s. I could save it into a file in the server and then read the file and send it through express. That would not help me as the attachment is not needed afterwards, and is a workaround which I do not like.

cs04iz1
  • 1,737
  • 1
  • 17
  • 30

2 Answers2

2

If you have the stream you can do the following to send it as attachment in express:

res.attachment('yourfile.xlsx'); stream.pipe(res);

Hyra
  • 798
  • 1
  • 5
  • 21
  • 1
    As I wrote above stream.pipe(res) gives an error. "Unhandled rejection Error: Cannot pipe. Not readable" – cs04iz1 May 31 '16 at 09:46
  • Any chance of a little more code so we can see the context? Such as how you create the stream. – Hyra May 31 '16 at 10:07
  • I added the creation of the stream. I am open to suggestions if you think I am not starting properly. – cs04iz1 May 31 '16 at 13:17
  • you need to do `createReadStream` to get the stream to the file. – KVISH Sep 05 '16 at 20:20
0

You can use Exceljs' default streaming XLSX Writer.

// construct a streaming XLSX workbook writer with styles and shared strings
var options = {
    stream: res // stream to server response
};
var workbook = new Excel.stream.xlsx.WorkbookWriter(options);

According to the document, the constructor takes an optional options object with the following fields:

  • stream: Specifies a writable stream to write the XLSX workbook to.
  • filename: If stream not specified, this field specifies the path to a file to write the XLSX workbook to.
Truong
  • 33
  • 1
  • 7