titleArr可以设置传入表头数组[ ' 1 ' , ' 2 ' ],来设置前几行样式文字居中,加粗(封装的js)
import * as XLSX from 'xlsx';
import * as XLSX_STYLE from 'xlsx-style' // Vue2 + Webpack
import XLSX_SAVE from "file-saver";
function s2ab(s) {
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;
};
// 根据dom导出表格
//idSelector 界面中的需要导出的DOMid, fileName导出的文件名称
// const exportExcel = {
export function exportToExcel(idSelector,titleArr){
if(titleArr.length === 0 ){
titleArr = ['1']
}
// 设置导出的内容是否只做解析,不进行格式转换 false:要解析, true:不解析
const xlsxParam = { raw: true }
let tableDom = document.querySelector(idSelector).cloneNode(true);
let tableHeader = tableDom.querySelector('.el-table__header-wrapper');
let tableBody = tableDom.querySelector('.el-table__body-wrapper');
tableHeader.childNodes[0].append(tableBody.childNodes[0]);
let headerDom = tableHeader.childNodes[0].querySelectorAll('th');
// 移除操作与附件节点
for (let key in headerDom) {
if (headerDom[key].innerText === '操作') {
headerDom[key].remove();
}
}
for (let key in headerDom) {
if (headerDom[key].innerText === '附件') {
headerDom[key].remove();
}
}
// 清理掉附件 和操作的button
let tableList = tableHeader.childNodes[0].childNodes[2].querySelectorAll('td');
for (let key = 0; key < tableList.length; key++) {
if (tableList[key].querySelectorAll('.el-button').length > 0) {
tableList[key].remove();
}
}
// 因为element-ui的表格的fixed属性导致多出一个table,会下载重复内容,这里删除掉
if (tableDom.querySelector('.el-table__fixed-right')){
tableDom.removeChild(table.querySelector('.el-table__fixed-right'));};
if (tableDom.querySelector('.el-table__fixed')){
tableDom.removeChild(table.querySelector('.el-table__fixed'));};
let webBook = XLSX.utils.table_to_book(tableHeader, xlsxParam);
const worksheet = webBook.Sheets.Sheet1
worksheet["!cols"] = [];
for (let key in worksheet) {
if (key == '!ref' || key == '!merges' || key == '!cols' || key == '!rows') {
continue
} else {
if(worksheet[key] instanceof Object){
worksheet[key].s = {
alignment: {
horizontal: "top", //水平居中对齐
vertical: "top",
wrapText: 1,
indent: 0
},
};
}
for (let i = 0; i < titleArr.length; i++) {
// if (key.replace(/[^0-9]/ig, '') === titleArr[i] || key.replace(/[^0-9]/ig, '') === '2' || key.replace(/[^0-9]/ig, '') === '3') {
if (key.replace(/[^0-9]/ig, '') == titleArr[i]) {
worksheet[key].s = {
alignment: {
horizontal: "center", //水平居中对齐
vertical: "center",
wrapText: 1,
indent: 0
},
font: {
bold: true,
numFmt: 0,
},
};
}
}
worksheet["!cols"].push({ wpx: 150 });
}
}
const wbout = XLSX_STYLE.write(webBook, {
type: 'binary',
bookType: 'xlsx'
});
const wbResult = new Blob([s2ab(wbout)], {
type: 'application/octet-stream'})
return wbResult
}
// }
// export default exportExcel
vue页面引入
XLSX_SAVE.saveAs( exportToExcel(".tableDetail",['1','2']),`工作清单汇总.xlsx`);