exceljs / exceljs

Excel Workbook Manager

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Too few data or empty worksheet generate malformed excel file

bluedge opened this issue · comments

In streaming mode I came across this bug. If you add only one row to a worksheet OR add a worksheet that you do not fill the Excel file will be malformed. See the exemple below, uncomment the second line of push() to see the bug vanish.
Note: removing the worksheet columns header produce the same bug.

var stream      = require('stream');
var util            = require('util');
var Excel           = require('exceljs');
var fs          = require('fs');

var writableStream  = fs.createWriteStream('./streamed1.xlsx');

var ExcelTransform = function(options) {
    stream.Transform.call(this, {
        writableObjectMode: true,
        readableObjectMode: false
    });
        this.workbook = options.workbook;
    var self = this;

    this.workbook.stream.on('readable', function() {
        var chunk = workbook.stream.read();
        self.push(chunk);
    });
    this.worksheet = options.worksheet;
}
util.inherits(ExcelTransform, stream.Transform);

ExcelTransform.prototype._transform = function(doc, encoding, callback) {
    this.worksheet.addRow({
        name: doc.name
    }).commit();
    callback();
};

ExcelTransform.prototype._flush = function(callback) {
    this.workbook.commit(); // final commit
};

// it's better to provide the workbook as a parameter to the ExcelTransform
var workbook = new Excel.stream.xlsx.WorkbookWriter();
var worksheet = workbook.addWorksheet('sheet 1');
worksheet.columns = [{
    header: 'Name',
    key: 'name'
}];

var rs = new stream.Readable({ objectMode: true });
rs.push({ name: 'one' });
// rs.push({ name: 'two' }); // uncomment me to see the bug vanish
rs.push(null);

rs.pipe(new ExcelTransform({
    workbook: workbook,
    worksheet: worksheet
})).pipe(writableStream);

Fixed in 0.2.43