1、安装xlsx、xlsx-style、file-saver三个包
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、封装导出处理函数
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;
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);
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);
}
var aLink = document.createElement("a");
aLink.href = url;
aLink.download = saveName || "";
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方法里面的代码
getExport() {
exportExcelData(this.tableDataOne,this.tableHeadOne,"绿色交易合同信息管理");
},
5、导出效果如下