vue 前端导出 excel
npm install xlsx-js-style
import XLSX from 'xlsx-js-style';
//导出数据
exportD(title,data,fileName){
title=["标题1","标题2","标题3","标题4","标题5","标题6"];
data=[["数据1","数据2","数据3","数据4","数据5","数据6"],
["数据1","数据2","数据3","数据4","数据5","数据6"],
["数据1","数据2","数据3","数据4","数据5","数据6"]
];
fileName = "测试前端导出"
// 创建一个新的工作簿
const wb = XLSX.utils.book_new();
// 创建带样式的表格数据
const headers =title;
// 设置字体大小和颜色 表头居中
const headerStyle = {
font: { sz: "14"},
fill: { fgColor: { rgb: "c7c7c7" } },
alignment:{vertical:'center',horizontal:'center' }
};
//将样式加入表头
const headerRows = [
headers.map((header) => ({ v: header, s: headerStyle }))
];
// 将数据转换为工作表
const ws_header = XLSX.utils.aoa_to_sheet(headerRows);
//设置宽度
const cols=[];
title.forEach(item =>{
cols.push({wch:20})
})
ws_header["!cols"]=cols
// 应用样式
XLSX.utils.sheet_add_aoa(ws_header, headerRows, {origin: "A1"});
// 可以选择为内容设置默认样式
const defaultStyle = { font: { sz: "12" } }; // 设置默认字体大小
XLSX.utils.sheet_add_aoa(ws_header, data, {origin: "A2", cell: defaultStyle});
// 将工作表添加到工作簿
XLSX.utils.book_append_sheet(wb, ws_header, "Header");
// 写入文件
XLSX.writeFile(wb, fileName+".xlsx");
}