【问题标题】:Creating and downloading .xls file from JSON从 JSON 创建和下载 .xls 文件
【发布时间】:2016-12-06 15:15:30
【问题描述】:

我有以下代码,应该将 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?

【问题讨论】:

  • 您是否遇到了特定错误?也许这是 mime 类型的问题?我还建议在文本编辑器中打开 .xlsx,甚至可能在那里检查 XML 以查看它是否有效。也许您必须对 JSON 格式进行一些处理才能使其与json2xls 一起使用。

标签: javascript angularjs json meteor blob


【解决方案1】:

这可以在服务器端完成:

  • 安装exceljs

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();
});

【讨论】:

  • 我确实像您介绍的那样,它有效,但前提是我将此网址直接放入浏览器。当我尝试使用 angular $http 下载它时,下载成功,但文件大了一倍,因此 excel 无法打开它:this.$http({ method: "GET", url: "/foo", }).then((response) => { var file = new File([response.data], "hello world.xlsx", { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" }); fileSaver.saveAs(file); })
猜你喜欢
  • 1970-01-01
  • 2017-11-13
  • 1970-01-01
  • 1970-01-01
  • 2010-09-25
  • 2021-09-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多