一、安装依赖
npm install xlsx --save
二、引入依赖
import XLSX from 'xlsx'
三、构造导出数据
exportExcel(){
const tHeader = ['姓名','性别','地址','手机号’];
const filterVal = ['name','sex','address','phone'];
//列宽
const cols = [{wpx:60},{wpx:60},{wpx:100},{wpx:60}];
const data =this.formatJson(filterVal,this.exportData);//this.exportData是需要导出的json数据
this.export_json_to_excel(tHeader,data,"个人信息表",cols);
},
formatJson ( filterVal,jsonData){
return jsonData.map(v => filterVal.map( j => v [ j ] ));
},
四、构造Excel
export_json_to_excel(tHeader,data,defaultTitle,cols){
data.unshift ( tHeader );
let ws_name = "Sheet1";
let wb = XLSX.utils.book_new();
let ws = XLSX.utils.aoa_to_sheet(data);
if(cols.lengths>0){
ws['!cols'] = cols; //设置列宽
}
wb.SheetNames.push(ws_name);
wb.Sheets[ws_name] = ws;
let result = XLSX.write(wb,{bookType:'xlsx',bookSST:false,type:'binary'});
let title = defaultTitle || '列表';
this.openDownloadDialog(new Blob(this.s2ab(result)],{type:"application/octet-stream"}),title+".xlsx");
},
五、下载Excel
openDownloadDialog(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);
},
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;
}