套件網址: https://github.com/SheetJS/js-xlsx/tree/19620da30be2a7d7b9801938a0b9b1fd3c4c4b00/demos/angular2
使用方式:
import { WorkBook, utils, writeFile, WorkSheet } from 'xlsx';
table = [
{
First: 'one',
Second: 'two',
Third: 'three',
Forth: 'four',
Fifth: 'five'
},
{
First: 'un',
Second: 'deux',
Third: 'trois',
Forth: 'quatre',
Fifth: 'cinq'
},
];
onClick() {
const json = this.replaceHeader(this.table);
/* generate worksheet */
// const ws: WorkSheet = utils.json_to_sheet(json);
const ws: WorkSheet = utils.aoa_to_sheet(this.setupAoa(this.table));
/* generate workbook and add the worksheet */
const wb: WorkBook = utils.book_new();
utils.book_append_sheet(wb, ws, 'Sheet1');
/* save to file */
writeFile(wb, 'SheetJS.xlsx');
}
private setupAoa(table) {
var jsonArray = [];
jsonArray.push(["This is a Ttile"]);
jsonArray.push(["第一", "第二", "第三", "第四", "第五"]);
for(var i = 0; i < this.table.length; i++) {
jsonArray.push([this.table[i].First, this.table[i].Second, this.table[i].Third, this.table[i].Forth, this.table[i].Fifth]);
}
return jsonArray;
}
其中 aoa_to_sheet 可以透過二維陣列對應 Excel 表格的內容(另外也可以使用 json_to_sheet,不過要自行加入表頭設定就比較困難)
有問題嗎?歡迎一起討論喔!