引入模块 "xlsx": "^0.18.5"
npm install xlsx
import * as XLSX from 'xlsx'
function autoWidthFunc(ws, data) {
const colWidth = data.map(row => row.map(val => {
var reg = new RegExp("[\\u4E00-\\u9FFF]+", "g");
if (val == null) {
return { wch: 10 }
} else if (reg.test(val)) {
return { wch: val.toString().length * 2 }
} else {
return { wch: val.toString().length }
}
}))
const result = colWidth[0]
for (let i = 1; i < colWidth.length; i++) {
for (let j = 0; j < colWidth[i].length; j++) {
if (result[j].wch < colWidth[i][j].wch) {
result[j].wch = colWidth[i][j].wch
}
}
}
ws['!cols'] = result
}
function jsonToArray(key, jsonData) {
return jsonData.map(v => key.map(j => { return v[j] }))
}
// 导出报表文件
export function exportArrayToExcel({ key, data, title, filename, autoWidth }) {
const wb = XLSX.utils.book_new()
const arr = jsonToArray(key, data)
arr.unshift(title)
const ws = XLSX.utils.aoa_to_sheet(arr)
if (autoWidth) {
autoWidthFunc(ws, arr)
}
XLSX.utils.book_append_sheet(wb, ws, filename)
XLSX.writeFile(wb, filename + '.xlsx')
}
excel导出使用
import { exportArrayToExcel } from "@/utils/excel";
import { ref } from "vue";
tableMun = [
{ id: 1, props: "name", info: "姓名",width: 100 },
{ id: 2, props: "card_id", info: "身份编号",width: 150 },
{ id: 3, props: "contact", info: "联系方式",width: 150 },
{ id: 4, props: "current_address", info: "现住地址",width: 200 },
{ id: 5, props: "reg_address", info: "户籍地址",width: 200 }]
const tableData = ref([])
const donloadExcel = () => {
/** 导出按钮操作 */
const params = {
title: tableMun.map((column) => column.info),// 标题
key: tableMun.map((column) => column.props),// 键值
data: tableData.value, // 数据源
autoWidth: true, //autoWidth等于true,那么列的宽度会适应那一列最长的值
filename: "数据导出",
};
exportArrayToExcel(params);
};
在页面中直接调用 donloadExcel 即可,如需要其他操作,可自行定义;