参考:https://blog.csdn.net/weixin_46112225/article/details/125302036
一、依赖安装
package.json文件中(版本号其实应该可以不限制,用最新的是OK的)
"dependencies": {
...
"xlsx": "^0.16.8"
},
或者 手动安装
# npm方式
npm install xlsx@0.16.8 --save
# yarn方式
yarn add xlsx@0.16.8
导入
import XLSX from 'xlsx';
二、简单使用
* 此处使用参考链接内容,本人未使用这种方式
此方法纯导出数据,没有其他设置,对导出的Excel表格没有要求时可以用这个方法最简便。
1 const data = XLSX.utils.json_to_sheet(tableData.value)//此处tableData.value为表格的数据 2 const wb = XLSX.utils.book_new() 3 XLSX.utils.book_append_sheet(wb, data, 'test-data')//test-data为自定义的sheet表名 4 XLSX.writeFile(wb,'test.xlsx')//test.xlsx为自定义的文件名
三、自定义表头
* 此处引用参考链接内容,同时对“hasOwnProperty”报错进行修复
1 import XLSX from 'xlsx'; 2 3 /* 4 * @description: 5 * @param {Object} json 服务端发过来的数据 6 * @param {String} name 导出Excel文件名字 7 * @param {String} titleArr 导出Excel表头 8 * @param {String} sheetName 导出sheetName名字 9 * @return: 10 */ 11 function exportExcel(json, name, titleArr, sheetName) { 12 /* convert state to workbook */ 13 const data = []; 14 const keyArray = []; 15 const getLength = function (obj) { 16 let count = 0; 17 for (const i in obj) { 18 // if (obj.hasOwnProperty(i)) { => error Do not access Object.prototype method 'hasOwnProperty' from target object no-prototype-builtins 19 if (Object.prototype.hasOwnProperty.call(obj, i)) { 20 count++; 21 } 22 } 23 return count; 24 }; 25 for (const key1 in json) { 26 // if (json.hasOwnProperty(key1)) { 27 if (Object.prototype.hasOwnProperty.call(json, key1)) { 28 const element = json[key1]; 29 const rowDataArray = []; 30 for (const key2 in element) { 31 // if (element.hasOwnProperty(key2)) { 32 if (Object.prototype.hasOwnProperty.call(element, key2)) { 33 const element2 = element[key2]; 34 rowDataArray.push(element2); 35 if (keyArray.length < getLength(element)) { 36 keyArray.push(key2); 37 } 38 } 39 } 40 data.push(rowDataArray); 41 } 42 } 43 // keyArray为英文字段表头 44 data.splice(0, 0, keyArray, titleArr); 45 console.log('excel_data', data); 46 const ws = XLSX.utils.aoa_to_sheet(data); 47 const wb = XLSX.utils.book_new(); 48 // 此处隐藏英文字段表头 49 const wsrows = [{ hidden: true }]; 50 ws['!rows'] = wsrows; // ws - worksheet 51 XLSX.utils.book_append_sheet(wb, ws, sheetName); 52 /* generate file and send to client */ 53 XLSX.writeFile(wb, name + '.xlsx'); 54 } 55 56 export { exportExcel };
1 // 此段代码写到你的页面中,点击导出后的方法 2 const downloadExcel = () => { 3 if (selectedDataArray.value.length == 0) { 4 ElMessage({ 5 message: '请选择要导出的问答记录!', 6 type: 'warning' 7 }); 8 } else { 9 const titleArr = ['序号', '名称', '类型', '方式', '问题', '答案', '时间']; 10 exportExcel(selectedDataArray.value, '这是标题', titleArr, '这是sheet名字'); 11 12 ElMessage({ 13 message: '导出完成!', 14 type: 'success' 15 }); 16 } 17 };
导出效果: