环境及插件配置:(理论上vue2应该也可以使用,没有试验过)
"vue": "^3.2.36",
"webpack": "^5.94.0",
"webpack-cli": "^5.1.4",
"file-saver": "^2.0.5",
"xlsx": "^0.18.5"
必须安装 file-saver 与 xlsx
该方法中用到了一个判断数据类型的小方法
* 判断数据类型* @param {any} value * @returns {String}* 返回数据为:* "[object Number]","[object String]","[object Boolean]","[object Date]","[object RegExp]"* "[object Object]","[object Array]","[object Function]","[object Null]","[object Undefined]"*/function getDataType(value) {return Object.prototype.toString.call(value)
}
将table表格导出为Excel
import * as XLSX from 'xlsx'
import { saveAs } from 'file-saver';function getDataType(value) {return Object.prototype.toString.call(value)
}/*** 将table表格导出为Excel* @param {Array} tableData 表格数据* @param {Array} tableHeader 表格头* @param {Object | String} exportConfig 导出的Excel文件配置信息* {* width:列宽,可传入list,传入多少列,即可设置多少列 widthList - 前三列:[120,120,120] 默认每一列宽度120* name: 导出文件的名称,默认当前日期 - xxxx年xx月xx日* }* String - 允许只传入文件名称* @param {Object} key 解析数据所需key: label - 表头显示字段 prop - 表格渲染字段* @returns {null}* 无返回*/function exportToExcel(tableData, tableHeader, exportConfig = {width: '120',widthList: [],name: "",
}, key = {label: 'label',prop: "prop"
}) {let exportList = [], // 导出目标headerLabelList = [], // 列头labelheaderPropList = [], // 列头propdataList = [], // 数据label = key?.label || 'label', // 表格label的keyprop = key?.prop || "prop"; // 表格prop的keytableHeader.forEach(item => {headerLabelList.push(item[label])headerPropList.push(item[prop])})tableData.forEach(item => {let itemList = []headerPropList.forEach(itemProp => {itemList.push(item[itemProp])})dataList.push([...itemList])})exportList = [headerLabelList, ...dataList]// 数据转换工作表const worksheet = XLSX.utils.aoa_to_sheet(exportList)let wsList = Array(tableHeader.length).fill({ wpx: '120' }) // 导出的Excel列宽let exportName = new Date().Format('yyyy-MM-dd') // 导出的文件名称 - 默认当天时间if (exportConfig) {if (getDataType(exportConfig) == "[object String]") {exportName = exportConfig} else if (getDataType(exportConfig) == "[object Object]") {if (getDataType(exportConfig.widthList) == '[object Array]' && exportConfig.widthList.length) {wsList = exportConfig.widthList.map(item => {return { wpx: item }})} else {let wpx = '120'if (exportConfig.width) {wpx = exportConfig.width}wsList = Array(tableHeader.length).fill({ wpx })}if (exportConfig?.name) {exportName = exportConfig.name}}}worksheet['!cols'] = wsList// 创建工作簿并添加转换好的工作表const workbook = XLSX.utils.book_new()XLSX.utils.book_append_sheet(workbook, worksheet, exportName)// 生成Excel文件const excelBuffer = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });// 使用blob和FileReader创建一个URL然后下载const dataBlob = new Blob([excelBuffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8' });saveAs(dataBlob, exportName + '.xlsx')
}export {exportToExcel
}