//小编最近在做vue前端列表数据导出到excel,掉了次坑,这里记录一下操作步骤。
//1,下载依赖
npm install --save xlsx
//2,编写导出方法成 js 文件,放到项目 utils 文件夹下面,js 文件名为 ExcelUtils.js
文件完整内容如下:
-------------------------------------------------------------------------------
import * as XLSX from 'xlsx'
//(这里需要用这种写法,如果改成 import XLSX from 'xlsx',
// 会报错 "export 'default' (imported as 'XLSX') was not found in 'xlsx')
function exportExcel(headers, data, fileName = '结果.xlsx') {
const _headers = headers.map((item, i) => Object.assign({},
{ key: item.key, title: item.title, position: String.fromCharCode(65 + i) + 1 }))
.reduce((prev, next) => Object.assign({}, prev,
{ [next.position]: { key: next.key, v: next.title } }), {})
const _data = data.map((item, i) => headers.map((key, j) => Object.assign({},
{ content: item[key.key], position: String.fromCharCode(65 + j) + (i + 2) })))
// 对刚才的结果进行降维处理(二维数组变成一维数组)
.reduce((prev, next) => prev.concat(next))
// 转换成 worksheet 需要的结构
.reduce((prev, next) => Object.assign({}, prev,
{ [next.position]: { v: next.content } }), {})
// 合并 headers 和 data
const output = Object.assign({}, _headers, _data)
// 获取所有单元格的位置
const outputPos = Object.keys(output)
// 计算出范围 ,["A1",..., "H2"]
const ref = `${outputPos[0]}:${outputPos[outputPos.length - 1]}`
// 构建 workbook 对象
const wb = {
SheetNames: ['mySheet'],
Sheets: {
mySheet: Object.assign({}, output, {
'!ref': ref,
'!cols': [{ wpx: 45 }, { wpx: 100 }, { wpx: 200 }, { wpx: 80 }, { wpx: 150 }, { wpx: 100 }, { wpx: 300 }, { wpx: 300 }],
}),
},
}
// 导出 Excel
XLSX.writeFile(wb, fileName)
}
export default { exportExcel }
-------------------------------------------------------------------------------------------
//3,功能页面引入js方法
import excelUtil from '@/utils/ExcelUtils'
//4,方法调用
this.useExportUtil(res.list)
(res.list 是通过后端接口调用获取的数据列表)
//5,方法实现
useExportUtil(data) {
const initColumn = [
{
title: '行员姓名',
dataIndex: 'userName',
key: 'userName',
className: 'text-monospace',
},
{
title: '移事通号',
dataIndex: 'userId',
key: 'userId',
},
{
title: '赋权时间',
dataIndex: 'createTime',
key: 'createTime',
},
{
title: '赋权人员ID',
dataIndex: 'createUser',
key: 'createUser',
},
{
title: '行员部门',
dataIndex: 'pathName',
key: 'pathName',
},
]
let attendanceInfoList = data
excelUtil.exportExcel(initColumn, attendanceInfoList, '权限名单.xlsx')
},
即可。
Vue 导出列表数据成 excel
最新推荐文章于 2024-05-07 17:21:27 发布