2016-08-01 53 views
-1

下載.xls文件我有以下的代碼,這應該編碼JSON對象XLSX,然後下載:創建和JSON

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

是否存在特定錯誤?也許這是一個MIME類型的問題?我還建議在文本編輯器中打開.xlsx,甚至可以將XML轉到那裏以查看它是否有效。也許你需要用JSON格式來處理'json2xls'。 – CodeChimp

回答

0

這是可以做到的服務器端:

  • 安裝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(); 
}); 
+0

我確實喜歡你的介紹和它的作品,但只有當我把這個網址直接放入瀏覽器。當我嘗試使用$ http下載它時,下載成功,但是該文件大了兩倍,因此excel無法打開它:'this。$ http({「http」, url:「/ foo」, (響應)=> var file = new File([response.data],「hello world.xlsx」,{type:「application/vnd.openxmlformats-officedocument.spreadsheetml.sheet」}) ; fileSaver.saveAs(file); })' – Katamaran