第一步:设置Element UI的table
import {
tableMethod
} from '@/libs/mixins'
ELEMENT.TableColumn.props.align.default = 'center'
// table右键事件
// 表头数据
Vue.set(ELEMENT.Table.props, 'tableHeadForExport', {
type: Array,
default: []
})
// 获取表格全部数据的方法
Vue.set(ELEMENT.Table.props, 'tableHeadForExportAllMethod', {
type: Function
})
// 导出表格的名称
Vue.set(ELEMENT.Table.props, 'excelNameForExport', {
type: String,
default: 'xx.xlsx'
})
// 表格设置完成之后触发的事件
Vue.set(ELEMENT.Table.props, 'afterSetTableHeadMethod', {
type: Function
})
ELEMENT.Select.props.filterable.default = true
ELEMENT.Dialog.props.closeOnClickModal.default = false
Vue.config.productionTip = false;
ELEMENT.Table.mixins.push(tableMethod)
第二步:设置vuex
第三步:设置全局方法
第四步:在全局页面统一处理
第五步:全局导出excel方法
// 制作excel文件
Vue.prototype.$makeExcel = (jsonData, fileName) => {
let wb = XLSX.utils.book_new()
let temp = XLSX.utils.json_to_sheet(jsonData)
// 设置第一行的行高
Vue.set(temp, '!rows', [{
hpx: 40
}])
// 设置行宽
let arr = []
const num = Object.keys(jsonData[0]).length
for (let i = 0; i < num; i++) {
arr.push({
wpx: 100
})
}
Vue.set(temp, '!cols', arr)
XLSX.utils.book_append_sheet(wb, temp, 'Sheet1');
// XLSX.writeFile(wb, 'SheetJS.xlsx');
// 单元格样式
let styleBase = {
font: {
name: '宋体',
sz: 10,
// color: {
// rgb: '00104E8B'
// }
},
numFmt: '#,##0.00',
alignment: {
vertical: "center",
horizontal: "center",
wrapText: true
},
border: { // 设置边框
top: {
style: 'thin'
},
bottom: {
style: 'thin'
},
left: {
style: 'thin'
},
right: {
style: 'thin'
}
}
}
// 表头样式
let styleBase2 = {
font: {
name: '宋体',
sz: 10,
bold: true,
color: {
rgb: 'ffffff'
}
},
fill: {
bgColor: {
rgb: '5aa1bf'
},
fgColor: {
rgb: '5aa1bf'
},
patternType: 'solid'
},
// numFmt:'#,##0.00',
alignment: {
vertical: "center",
horizontal: "center",
wrapText: true
},
border: { // 设置边框
top: {
style: 'thin'
},
bottom: {
style: 'thin'
},
left: {
style: 'thin'
},
right: {
style: 'thin'
}
}
}
for (const key in temp) {
if (temp.hasOwnProperty(key)) {
if (!key.startsWith('!')) {
if (/^[A-Z]+1$/.test(key)) {
Vue.set(temp[key], 's', styleBase2)
} else if (temp[key] && temp[key].t) {
Vue.set(temp[key], 's', styleBase)
}
}
}
}
try {
let file = XLSX2.write(wb, {
bookType: "xlsx",
bookSST: false,
// type: "base64",
type: "binary",
// cellStyles: true
});
saveAs(
//Blob 对象表示一个不可变、原始数据的类文件对象。
//Blob 表示的不一定是JavaScript原生格式的数据。
//File 接口基于Blob,继承了 blob 的功能并将其扩展使其支持用户系统上的文件。
//返回一个新创建的 Blob 对象,其内容由参数中给定的数组串联组成。
// new Blob([wbout], { type: "application/octet-stream" }),
// new Blob([this.base64ToUint8Array(file)], { type: "text/plain;charset=utf-8" }),
new Blob([s2ab(file)], {
type: "application/octet-stream"
}),
//设置导出文件名称
fileName
);
} catch (e) {
if (typeof console !== "undefined") console.log(e);
}
}
function s2ab(s) {
let buf = new ArrayBuffer(s.length);
let view = new Uint8Array(buf);
for (let i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
return buf;
}
第六步:页面使用 (restMethod为页面刷新方法)
附图:效果图和导出的excel文件