60
rated 0 times
[
61]
[
1]
/ answers: 1 / hits: 21845
/ 8 Years ago, mon, february 8, 2016, 12:00:00
I'm using ExcelJS module and writing wrapper for my purposes, which implements Transform Stream API (yes, node version is 0.10.40).
ExcelJS has a stream API and according to example in ExcelJS module we can use one like this (execute node index.js > test.xlsx
):
var stream = require('stream'),
Excel = require('exceljs');
var rs = new stream.Readable({objectMode: true});
rs.push({name: 'one'});
rs.push({name: 'two'});
rs.push({name: 'three'});
rs.push(null);
var workbook = new Excel.stream.xlsx.WorkbookWriter({stream: process.stdout}),
worksheet = workbook.addWorksheet('sheet 1');
worksheet.columns = [{header: 'Name', key: 'name'}];
rs.on('data', function(doc) {
worksheet.addRow({
name: doc.name
}).commit();
});
rs.on('end', function(doc) {
worksheet.commit();
workbook.commit();
});
And it is working fine, but looks not very clean. Because we cannot use .pipe
.
What I need:
'use strict';
var buffer = require('buffer'),
stream = require('stream'),
util = require('util'),
Excel = require('exceljs');
var rs = new stream.Readable({objectMode: true});
rs.push({name: 'one'});
rs.push({name: 'two'});
rs.push({name: 'three'});
rs.push(null);
var ExcelTransform = function(options) {
stream.Transform.call(this, options);
this._writableState.objectMode = true;
this._readableState.objectMode = false;
this.workbook = new Excel.stream.xlsx.WorkbookWriter({stream: this});
this.worksheet = this.workbook.addWorksheet('sheet 1');
this.worksheet.columns = [{header: 'Name', key: 'name'}];
};
util.inherits(ExcelTransform, stream.Transform);
ExcelTransform.prototype._transform = function(chunk, encoding, callback) {
if (buffer.Buffer.isBuffer(chunk)) {
this.push(chunk);
} else {
this.worksheet.addRow({
name: chunk.name
}).commit();
}
callback();
};
ExcelTransform.prototype._flush = function(callback) {
this.worksheet.commit();
this.workbook.commit();
callback();
};
rs.pipe(new ExcelTransform()).pipe(process.stdout);
But this is not working and giving me empty output.
More From » node.js