我有以下代码,它应该将JSON对象编码为XLSX,然后下载它:
this.data = {
foo: "xyz"
}
let json2xls = require('json2xls');
var data = json2xls(this.data);
let blob = new Blob([data], { type: "binary" });
let a = angular.element("a");
a.attr("href", this.$window.URL.createObjectURL(blob));
a.attr("download", "myfile.xlsx");
a[0].click();
它确实创建并下载了一个文件,但是excel无法打开它。
我确信下面的转换方法有效,因为我可以将this.data
发送到服务器,使用fs.writeFile()
保存,然后下载此文件。
var data = json2xls(this.data);
如何从JSON解析为XLS,然后将其作为XLS保存在浏览器中?
答案 0 :(得分:0)
这可以在服务器端完成:
meteor npm install -s exceljs
import Excel from 'exceljs';
WebApp.connectHandlers.use('/your-download-url', function(req, res, next) {
// Use params to specify parameters for the xls generation process...
const params = req.url.split('/');
// ... for example /your-download-url/your-user-id
// params[0] will be 'your-download-url'
const user = Meteor.users.findOne(params[1]);
const workbook = new Excel.stream.xlsx.WorkbookWriter({});
workbook.created = new Date();
workbook.modified = new Date();
const sheet = workbook.addWorksheet('Your sheet name');
res.writeHead(200, {
'Content-Disposition': `attachment;filename=${filename}`,
'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
});
workbook.stream.pipe(res);
const headers: [
{ header: 'Column 1', key: 'col1', width: 20 },
{ header: 'Column 2', key: 'col2', width: 15 },
];
sheet.columns = headers;
// User sheet.addRow(rowData) to add each row in your sheet.
workbook.commit();
});