JS table下载
时间紧任务重推荐第一种,直接把表格整个拿过来;第二种根据表格的配置和数据进行设置1、html下载,原生JS
downTable(name) {
const uri = 'data:application/vnd.ms-excel;base64,',
template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head></head><body><table>{table}</table></body></html>',
base64 = function (s) {
return window.btoa(unescape(encodeURIComponent(s)))
},
format = function (s, c) {
return s.replace(/{(\w+)}/g,
function (m, p) {
return c;
})
}
//el-table表格设置列浮动,会多出一个隐藏table,需要过滤掉
const table = document.getElementById('table')?.innerHTML.replace(/[\s\S]*?<\/div>/img, "");
const ctx = {worksheet: name || 'Worksheet', table}
// 通过创建a标签实现
const link = document.createElement("a");
link.href = uri + base64(format(template, ctx));
// 对下载的文件命名
link.download = name + '.xlsx';
link.click();
}
优点:快
缺点:时间会被转义,样式会受页面CSS影响
2、XLSX
async downTable(type: number) {
let tableColumn: any[] = [], tableData: any[] = [], fileName = '';
if (type === 1) {
tableColumn = this.trendSaleColumn;
tableData = this.trendSaleData;
fileName = '售前介入趋势(销售).xlsx';
}else if (type === 3) {
await this.getPreSalesConvertInfo(this.transferSaleType, 1);
tableColumn = this.transferSaleColumn;
tableData = this.transferSaleData;
fileName = '售前部门转化(销售).xlsx';
}
let data: any[] = [[]];
tableColumn.forEach((item: any) => {
data.push(item.label);
})
tableData.forEach((item: any) => {
let row: any[] = [];
tableColumn.forEach((column: any) => {
row.push(item);
})
data.push(row);
})
const sheet = XLSX.utils.aoa_to_sheet(data);<br> //合并单元格配置,需要计算需要合并的行列数
if (type === 3 || type === 4) {
if (this.productType > 0 && this.productType > 0) {
sheet['!merges'] = [
{s: {r: 1, c: 0}, e: {r: this.productType, c: 0}},//s表示开始,e表示结束,r表示行,c表示列;
{s: {r: this.productType + 1, c: 0}, e: {r: this.productType, c: 0}}
];
} else if (this.productType > 0 || this.productType > 0) {
sheet['!merges'] = [
{s: {r: 1, c: 0}, e: {r: this.productType || this.productType, c: 0}},//s表示开始,e表示结束,r表示行,c表示列;
];
}
}
// 通过创建a标签实现
const link = document.createElement("a");
link.href = URL.createObjectURL(sheet2blob(sheet));
// 对下载的文件命名
link.download = fileName;
link.click();
}sheet2blob(sheet: any, sheetName: string = 'sheet1') {
const workbook: any = {
SheetNames: ,
Sheets: {}
};
workbook.Sheets = sheet;
// 生成excel的配置项
const wopts: any = {
bookType: 'xlsx', // 要生成的文件类型
bookSST: false, // 是否生成Shared String Table,官方解释是,如果开启生成速度会下降,但在低版本IOS设备上有更好的兼容性
type: 'binary'
};
const wbout = XLSX.write(workbook, wopts);
const blob = new Blob(, {type: "application/octet-stream"});
// 字符串转ArrayBuffer
function s2ab(s: any) {
const buf = new ArrayBuffer(s.length);
const view = new Uint8Array(buf);
for (let i = 0; i != s.length; ++i) view = s.charCodeAt(i) & 0xFF;
return buf;
}
return blob;
}
优点:单元格内容可控,可以设置单元合并等XLSX支持的配置
缺点:复杂表格需要计算合并单元格的位置和数量,比如多级表头
来源:https://www.cnblogs.com/gxp69/p/17123638.html
免责声明:由于采集信息均来自互联网,如果侵犯了您的权益,请联系我们【E-Mail:cb@itdo.tech】 我们会及时删除侵权内容,谢谢合作!
页:
[1]