1.安装以下依赖:
npm install xlsx file-saver -S
npm install script-loader -S -D2. 在项目中创建 Export2Excel.js 文件
参数
| 参数 | 说明 | 类型 | 可选值 | 默认值 |
|---|---|---|---|---|
| header | 导出数据的表头 | Array | / | [] |
| data | 导出的具体数据 | Array | / | [] |
| filename | 导出文件名 | String | / | excel-list |
| autoWidth | 单元格是否要自适应宽度 | Boolean | true / false | true |
| bookType | 导出文件类型 | String | xlsx, csv, txt, more | xlsx |
3. 使用:
// 表格导出
export2Excel () {
this.$NProgress.start() // 进度条
import('@/utils/Export2Excel').then(excel => {
const tHeader = ['产品编号', '名称', '大类', '小类', '规格', '单位', '获取途径', '状态']
const filterVal = ['code', 'name', 'productCategoryTopName', 'productCategorySecondName',
'spec', 'unitName', 'productAccessName', 'status']
const list = this.list
// 数据处理
const data = this.formatJson(filterVal, list)
// 参数
excel.export_json_to_excel({
header: tHeader, // 表头
data, // 数据源
filename: 'excel-list', // 文件名称
autoWidth: true, // 宽度是否自动
bookType: 'xlsx' // 文件格式
})
this.$NProgress.done()
})
},
formatJson (filterVal, jsonData) {
return jsonData.map(v => filterVal.map(j => v[j]))
}4. 实用实例