概述
js-xlsx是一个前端excel表格数据解析处理插件,兼容性非常好。
该插件github地址为:https://github.com/SheetJS/js-xlsx
Angular2中使用XLSX导出表格到本地
将表格数据,一个二维数组传入exportExcel
方法的data即可,自动下载excel文件。
import * as XLSX from 'xlsx';
export class Excel {
exportExcel(data: any[], filename = 'export.xlsx') {
const ws_name = "SheetJS";
// generate worksheet
const ws: XLSX.WorkSheet = XLSX.utils.aoa_to_sheet(data);
// generate workbook and add the worksheet
const wb: XLSX.WorkBook = XLSX.utils.book_new();
// add worksheet to workbook
XLSX.utils.book_append_sheet(wb, ws, ws_name);
// write workbook
// XLSX.writeFile(wb, filename);
// generate Blob
const wbout: ArrayBuffer = XLSX.write(wb, {bookType: 'xlsx', type: 'array'});
const blob: Blob = new Blob([wbout], {type: 'application/octet-stream'});
// save file
let link = document.createElement('a');
link.href = URL.createObjectURL(blob);
link.download = filename;
link.click();
setTimeout(function() {
// 延时释放掉obj
URL.revokeObjectURL(link.href);
link.remove();
}, 500);
}
}
如果在nodejs端,还可以使用下面的更简单的方法:
/* generate worksheet */
const ws: XLSX.WorkSheet = XLSX.utils.aoa_to_sheet(this.data);
/* generate workbook and add the worksheet */
const wb: XLSX.WorkBook = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');
/* save to file */
XLSX.writeFile(wb, 'SheetJS.xlsx');
一般JS中导出表格方法
导入JS:https://cdnjs.com/libraries/xlsx
<script lang="javascript" src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.12.12/xlsx.full.min.js"></script>
<script>
function exportExcel(data) {
const filename = 'redExcel.xlsx';
const ws_name = "SheetJS";
const worksheet = XLSX.utils.aoa_to_sheet(data);
const workbook = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(workbook, worksheet, ws_name);
// generate Blob
const wbout = XLSX.write(workbook, {bookType: 'xlsx', type: 'array'});
const blob = new Blob([wbout], {type: 'application/octet-stream'});
// save file
let link = document.createElement('a');
link.href = URL.createObjectURL(blob);
link.download = filename;
link.click();
setTimeout(function() {
// 延时释放掉obj
URL.revokeObjectURL(link.href);
link.remove();
}, 500);
}
</script>