我正在使用ExcellJS用于在 Node.js 上操作 Excell 的库(Hapi.js)。
我让它根据上传的文件创建工作表。我做了这样的事情:
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
的流。然后你就可以处理 promise 了。
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.
关于javascript - Excelljs - 如何从流创建工作表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36125970/