1、安装xlsx、xlsx-style、file-saver三个包
//xlsx与file-saver指定版本安装,解决默认安装utils未定义的问题
npm install --save xlsx@0.17.0
npm install --save file-saver@2.0.5
npm install xlsx-style --save
2、在使用的页面引入
import XLSX from 'xlsx' // 导入导出都要用到的插件
import FileSaver from 'file-saver' // 导出需要用到的插件
import XLSXStyle from 'xlsx-style';//导出引入样式
3、封装导出处理函数
//导出excel文件-并修改表头样式
export function exportExcelData(data,titles,filename){
Object.prototype.toString.call();
let proV = toString.call(titles[0]);
let headerValue = proV === '[object Object]' ? toArray(titles,'value') : titles;//表头value
let headerName = proV === '[object Object]' ? toArray(titles,'name') : titles;//表头名称
let dataArr = [headerName];//表格数据
for (let i = 0; i< data.length; i++){
let arr = headerValue.map((item,index)=>{
return data[i][item];
});
dataArr.push(arr)
}
var sheet = XLSX.utils.json_to_sheet(dataArr, {
skipHeader: true,
});
/**设置标题头背景色 */
for (const key in sheet) {
// 第一行,表头
if (key.replace(/[^0-9]/ig, '') === '1') {
sheet[key].s = {
fill: { //背景色
fgColor: {
rgb: 'C0C0C0'
}
},
font: {//字体
name: '宋体',
sz: 12,
bold: true
},
border: {//边框
bottom: {
style: 'thin',
color: '#9a9a9a'
}
},
alignment:{
horizontal:'center' //水平居中
}
}
}else if (Number(key.replace(/[^0-9]/ig, '')) > 1){
sheet[key].s = {
alignment:{
horizontal:'center' //水平居中
}
}
}
let colsP = headerName.map((item,index)=>{
let obj = {
'wch': 20 //列宽
}
if (item == '序号'){
obj['wch'] = 10
}else {
obj['wch'] = 18
}
return obj;
})
sheet['!cols'] = colsP;//列宽
}
openDownload(sheet2blob(sheet,filename), filename+".xlsx");
}
function sheet2blob(sheet, sheetName) {
let wb = XLSX.utils.book_new();
wb.SheetNames.push(sheetName)
wb.Sheets[sheetName] = sheet;
var wbout = XLSXStyle.write(wb, { bookType: '', bookSST: false, type: 'binary' })
var blob = new Blob([s2ab(wbout)], { type: "" },sheetName);
// 字符串转ArrayBuffer
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;
}
return blob;
}
function openDownload(url, saveName) {
if (typeof url == "object" && url instanceof Blob) {
url = URL.createObjectURL(url); // 创建blob地址
}
var aLink = document.createElement("a");
aLink.href = url;
aLink.download = saveName || ""; // HTML5新增的属性,指定保存文件名,可以不要后缀,注意,file:///模式下不会生效
var event;
if (window.MouseEvent) event = new MouseEvent("click");
else {
event = document.createEvent("MouseEvents");
event.initMouseEvent(
"click",
true,
false,
window,
0,
0,
0,
0,
0,
false,
false,
false,
false,
0,
null
);
}
aLink.dispatchEvent(event);
}
4、vue页面引入使用
import {exportExcelData} from '@/utils/index.js'
methods方法里面的代码
// 导出按钮触发事件
//this.tableDataOne:表格数据;this.tableHeadOne:表头;"绿色交易合同信息管理":导出文件名称
getExport() {
exportExcelData(this.tableDataOne,this.tableHeadOne,"绿色交易合同信息管理");
},
5、导出效果如下