一、安装 依赖
npm install file-saver //安装文件保存依赖
npm install xlsx //保存为xlsx需要安装
npm install html2canvas //保存为图片需要安装
二、封装函数
import { saveAs } from "file-saver"
import * as XLSX from 'xlsx'
import html2canvas from 'html2canvas'
/*
把表格保存为excel文件
name:文件名,包括文件后缀
id:要保存为excel的表格id名,格式为 #id名
*/
export const exportExcel = (name, id) => {
const sheetBlob = XLSX.write(XLSX.utils.table_to_book(document.querySelector(id)), {
type: 'array',
bookType: 'xlsx',
bookSST: true
});
try {
saveAs(new Blob([sheetBlob], { type: 'application/octet-stream'}), name);
} catch (error) {
window.console.log(error);
}
return sheetBlob;
}
/*
把表格保存为png图片
name:图片名,包括文件后缀
id:要保存为png图片的表格id名,格式为 #id名
*/
export const exportPng = (name, id) => {
try {
/*
html2canvas只能把表格可见部分转化为图片,有时表格过长,存在横向滚动条,拖动滚动条才能看见的表格部分,不能转化为图片;通过JS拼出完整表格,可解决这一问题。
*/
//不使用cloneNode(true)会导致拼好表格的时候,页面表格消失
let tHead = document.querySelector(id + ' table.el-table__header').cloneNode(true), tBody = document.querySelector(id + ' table.el-table__body').cloneNode(true), table = document.createElement('div'), deviceTdList = [];
table.id = 'table'; //为拼的表格设置id,使html2canvas可以选中拼的表格并将其转化为图片
/*
克隆并拼凑页面表格,拼凑出的表格会丢失页面表格的样式,给拼凑表格设计与页面表格一样的样式
*/
tHead.style.height = '46px';
tHead.style.borderTop = '1px solid #DAE1F1';
tHead.style.borderBottom = '1px solid #DAE1F1';
tHead.style.borderLeft = '1px solid #DAE1F1';
tBody.style.borderLeft = '1px solid #DAE1F1';
table.appendChild(tHead);
table.appendChild(tBody);
document.body.appendChild(table); //将拼凑表格插入页面
document.querySelectorAll('#table>table:first-child th').forEach((th, index) => {
th.style.borderRight = '1px solid #DAE1F1';
Boolean(index % 2) ? th.style.paddingLeft = '10px' : '';
});
document.querySelectorAll('#table>table td').forEach(td => {
td.style.borderRight = '1px solid #DAE1F1';
td.style.borderBottom = '1px solid #DAE1F1';
td.style.textAlign = 'center';
});
document.querySelectorAll('#table>table:last-child td.device-table-content').forEach(td => {
td.style.verticalAlign = 'top';
});
document.querySelectorAll('#table>table:last-child td.device-table-content tr>td').forEach((td, index) => {
td.style.textAlign = 'left';
Boolean(index % 2) ? td.style.borderRight = 'none' : '';
});
/* 使用html2canvas选中拼凑表格转化为png图片保存 */
html2canvas(document.querySelector('#table')).then(canvas => {
saveAs(canvas.toDataURL('image/png'), name);
}).catch(error => {
console.log(error);
}).finally(() => {
document.body.removeChild(table); //将拼凑表格从页面中移除
});
} catch (error) {
console.log('导出失败', error);
}
}