Excelljs - 如何从流创建 sheet

Excelljs - how to create a sheet from stream

我正在使用 ExcellJS 库在 Node.js(Hapi.js).

上操作 Excell

我知道它可以根据上传的文件创建工作表。我做了这样的事情:

uploadItems: function (request, reply) {
    var data = request.payload;
    if (data.file) {
        var name = data.file.hapi.filename;
        //var path = __dirname + "/uploads/" + name;
        var path = process.cwd() + "/uploads/" + name;
        var file = fs.createWriteStream(path);

         data.file.on('end', function (err) {
        var workbook = new Excel.Workbook();
        var bulkParts = [];
        workbook.xlsx.readFile(path)
            .then(function (workbook) {
                workbook.eachSheet(function (worksheet, sheetId) {
                    worksheet.eachRow({includeEmpty: true}, function (row, rowNumber) {
                        var singleItem = new _Items(data.ProductId, row.values[1], row.values[2]);
                        bulkParts.push(singleItem);
                        console.log("Row " + rowNumber + " = " + JSON.stringify(row.values));
                    });
                });
        file.on('error', function (err) {
            console.error(err)
        });
        data.file.pipe(file);
    }
         ...

这行得通。这个方法从流创建一个文件,然后我读取这个文件并创建我的对象。我宁愿直接从流创建一个文件,从而避免在磁盘上创建。

Documentation 的 Excell 插件提到了这一点:

// pipe from stream 
var workbook = new Excel.Workbook();
stream.pipe(workbook.xlsx.createInputStream());

但老实说,我尝试了很多方法,就是无法让它从流中创建对象。 感谢任何帮助。

确保您的 upload route is configured properly 接受文件流。 在下面的示例中,request.payload.file 是您传递到 workbook.xlsx.read 的流。然后你可以处理承诺。

var uploadRoute = {
    method: 'POST',
    path: '/upload',
    config: {
        validate: {
            payload: {
                file: joi.any()
            }
        },
        payload: {
            maxBytes: 30009715200,
            output: 'stream',
            parse: true,
            allow: 'multipart/form-data'
        },
        description: 'upload an excel file'
    },
    handler: uploadRouteHandler
};

function uploadRouteHandler(request, reply) {

    if (request.payload.file) { // request.payload.file is your stream
        var workbook = new Excel.Workbook();

        workbook.xlsx.read(request.payload.file)
                .then(function(excelworkbook) {
                     /** do stuff with your new workbook here **/
                });
    }
}

'stream' - the incoming payload is made available via a Stream.Readable interface. If the payload is 'multipart/form-data' and parse is true, fields values are presented as text while files are provided as streams. File streams from a 'multipart/form-data' upload will also have a property hapi containing filename and headers properties.