导出效果如下图所示:
下载xlsx
npm install xlsx
angular.json中引入:
"node_modules/xlsx/dist/xlsx.full.min.js",
"src/assets/js/jszip.js",
"src/assets/js/xlsx.js"
两个插件地址:
上传中,等下更新
typings.d.ts中需要加一下声明
ts代码:
export(){
var wb = XLSX.utils.table_to_book(document.getElementById("tableDataId"), { sheet: "Sheet JS", raw: true });
let range = XLSX.utils.decode_range(wb.Sheets['Sheet JS']['!ref']);
// let borderStyle = {
// top: {
// style: "thin",
// color: { rgb: "000000" }
// },
// bottom: {
// style: "thin",
// color: { rgb: "000000" }
// },
// left: {
// style: "thin",
// color: { rgb: "000000" }
// },
// right: {
// style: "thin",
// color: { rgb: "000000" }
// }
// }
// wb.Sheets['Sheet JS']['!rows'] = [{ hpx: 150 }, { hpx: 50 }, { hpx: 50 }, { hpx: 50 }, { hpx: 50 }, { hpx: 50 }]
const numColumns = 100;
wb.Sheets['Sheet JS']['!cols'] = Array(numColumns).fill({ wpx: 160 });
wb.Sheets['Sheet JS']["!merges"].forEach((item: any) => {
if (item.e.r == item.s.r && item.e.c != item.s.c) {
// 列合并
let R = item.s.r;
let countLength = item.e.c - item.s.c;
for (let i = item.s.c; i <= item.e.c; i++) {
let cell = { c: i, r: R };
let cell_ref = XLSX.utils.encode_cell(cell);
if (!wb.Sheets['Sheet JS'][cell_ref]) {
wb.Sheets['Sheet JS'][cell_ref] = { t: "s", v: "" };
}
}
} else if (item.e.c == item.s.c && item.e.r != item.s.r) {
// 行合并
let C = item.s.c;
let countLength = item.e.r - item.s.r;
for (let i = item.s.r; i <= item.e.r; i++) {
let cell = { c: C, r: i };
let cell_ref = XLSX.utils.encode_cell(cell);
if (!wb.Sheets['Sheet JS'][cell_ref]) {
wb.Sheets['Sheet JS'][cell_ref] = { t: "s", v: "" };
}
}
}
})
console.log();
for (let C = range.s.c; C <= range.e.c; ++C) {
for (let R = range.s.r; R <= range.e.r; ++R) {
let cell = { c: C, r: R };
let cell_ref = XLSX.utils.encode_cell(cell);
console.log(wb.Sheets['Sheet JS'][cell_ref]);
wb.Sheets['Sheet JS'][cell_ref].s = {
alignment: {
horizontal: 'center', // 水平居中
vertical: 'center', // 垂直居中
wrapText: 1, // 文本自动换行
},
font: {
name: "黑体",
sz: "15",
bold: true
},
// border: borderStyle,
};
}
}
var wopts = { bookType: 'xlsx', bookSST: false, type: 'binary' };
var wbout = XLSXX.write(wb, wopts);// 使用xlsx-style 写入
saveAs(new Blob([s2ab(wbout)], { type: "" }), this.selectTitle[this.selectTitle.length-1]+".xlsx")
function s2ab(s: any) {
var buf = new ArrayBuffer(s.length);
var view = new Uint8Array(buf);
for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
return buf;
}
}
html:
<table id="tableDataId">
<tr></tr>
<table>