优势:简单便捷,易上手,开箱即用;javascript
缺点:不支持 excel 表格样式设置,且支持功能比较单一;html
优势:支持格式众多,支持 excel 表格样式设置,功能强大,可控性高,可读取和导出excel;vue
缺点:使用较为复杂,上手成本较大,且高级功能须要收费,但该功能能够借助 xlsx-style 实现;java
npm install -S vue-json-excel
复制代码
import Vue from "vue";
import JsonExcel from "vue-json-excel";
Vue.component("downloadExcel", JsonExcel);
复制代码
在须要触发导出事件的外出包裹 download-excel 组件ios
该组件支持的属性可参考vue-json-excel 的 github 文档git
<download-excel :data="json_data">
Download Data
<img src="download_icon.png" />
</download-excel>
复制代码
首先须要处理导出到 excel 文件的数据内容,分别是如下数据:github
let json_fields = {
// fieldLabel(表头名),attributeName(对应字段名)
fieldLabel: attributeName,
// 使用回调自定义导出数据
anotherFieldLabel: {
field: anotherAttributeName,
callback: (value) => {
return `formatted value ${value}`;
},
},
};
let json_data = [
{
attributeName: value1,
anotherAttributeName: value2
},
{
attributeName: value3,
anotherAttributeName: value4
}
];
复制代码
处理完数据以后则能够将数据传入 download-excel 组件中,该组件没有任何样式,只须要设置内部包裹的元素样式便可;web
<download-excel class="btn btn-default" :data="json_data" :fields="json_fields" worksheet="My Worksheet" name="filename.xls" >
Download Excel (you can customize this with html code!)
</download-excel>
复制代码
然而在实际的业务场景下,导出表格数据一般是导出表格的全部数据,因此在导出的过程当中,须要调用请求接口去获取表格中的全部数据,而调用接口获取数据是异步执行的过程,该插件也针对这个场景提供了解决方案。npm
相关案例:json
<template>
<div id="app">
<downloadexcel class = "btn" :fetch = "fetchData" :fields = "json_fields" :before-generate = "startDownload" :before-finish = "finishDownload">
Download Excel
</downloadexcel>
</div>
</template>
<script> import downloadexcel from "vue-json-excel"; import axios from 'axios'; export default { name: "App", components: { downloadexcel, }, data(){ return { json_fields: { 'Complete name': 'name', 'Date': 'date', }, } }, //data methods:{ async fetchData(){ const response = await axios.get(URL); return response.data.holidays; }, startDownload(){ alert('show loading'); }, finishDownload(){ alert('hide loading'); } } }; </script>
复制代码
因为这部分涉及内容较多,后续有须要会封装该功能
这里只对封装的 export2Excel 使用方法进行说明,暂时不对原理进行讲解。
该插件不只支持 excel 文件的导出,也支持文件导入功能,而且导出 excel 文件的不只支持 json 数据,也支持 table 导出;
因为 sheetjs-xlsx 提供的工具库其高级功能是付费项目,如修改表格样式等功能,所以选用了基于 sheetjs-xlsx 实现的 xlsx-style 插件。
兼容性:
npm install -S xlsx
npm install -S xlsx-style
复制代码
而 xlsx-style 插件在使用的时候会报错,官方也对该问题给出了解决方案,就是在根目录下的vue.config.js配置文件添加以下代码:
module.exports = {
configureWebpack: {
externals: {
'./cptable': 'var cptable'
}
}
}
复制代码
还有一种方案是改源代码,但不推荐使用,就不作说明了。
这里封装了导出 excel 文件的方法,其中,文件下载的功能有两个方案实现,分别是:
js-xlsx 插件自带了相关的函数去方便实现不一样数据格式的转换:
aoa_to_sheet
converts an array of arrays of JS data to a worksheet.json_to_sheet
converts an array of JS objects to a worksheet.table_to_sheet
converts a DOM TABLE element to a worksheet.sheet_add_aoa
adds an array of arrays of JS data to an existing worksheet.sheet_add_json
adds an array of JS objects to an existing worksheet.下面是封装的 export2Excel 函数具体代码,只须要将代码复制到建立的 export2Excel.js 文件中便可:
/** * create by lwj * @file 导出export插件封装 */
import * as styleXLSX from 'xlsx-style'
/** * 将 String 转换成 ArrayBuffer * @method 类型转换 * @param {String} [s] wordBook内容 * @return {Array} 二进制流数组 */
function s2ab (s) {
let buf = null;
if (typeof ArrayBuffer !== 'undefined') {
buf = new ArrayBuffer(s.length);
let view = new Uint8Array(buf);
for (let i = 0; i != s.length; ++i) {
view[i] = s.charCodeAt(i) & 0xFF;
}
return buf;
}
buf = new Array(s.length);
for (let i = 0; i != s.length; ++i) {
// 转换成二进制流
buf[i] = s.charCodeAt(i) & 0xFF;
}
return buf;
}
/** * 方案一:利用 URL.createObjectURL 下载 (如下选用) * 方案二:经过 file-saver 插件实现文件下载 * @method 文件下载 * @param {Object} [obj] 导出内容 Blob 对象 * @param {String} [fileName] 文件名 下载是生成的文件名 * @return {void} */
function saveAs (obj, fileName) {
let aLink = document.createElement("a");
if (typeof obj == 'object' && obj instanceof Blob) {
aLink.href = URL.createObjectURL(obj); // 建立blob地址
}
aLink.download = fileName;
aLink.click();
setTimeout(function () {
URL.revokeObjectURL(obj);
}, 100);
}
/** * @method 数据导出excel * @param {Object} [worksheets] 工做表数据内容 * @param {String} [fileName='ExcelFile'] 导出excel文件名 * @param {String} [type='xlsx'] 导出文件类型 */
export default function export2Excel ({ worksheets, fileName = 'ExcelFile', type = 'xlsx' } = {}) {
let sheetNames = Object.keys(worksheets);
let workbook = {
SheetNames: sheetNames, //保存的工做表名
Sheets: worksheets
};
// excel的配置项
let wopts = {
bookType: type, // 生成的文件类型
bookSST: false, // 是否生成Shared String Table,官方解释是,若是开启生成速度会降低,但在低版本IOS设备上有更好的兼容性
type: 'binary'
}
// attempts to write the workbook
let wbout = styleXLSX.write(workbook, wopts);
let wbBlob = new Blob([s2ab(wbout)], {
type: "application/octet-stream"
});
saveAs(wbBlob, fileName + '.' + type);
}
复制代码
须要注意几个问题:
而后只须要在须要导出 excel 的地方调用便可,若是对导出表格样式有要求的状况下,能够去了解如何配置表格样式,具体配置方法能够去 xlsx-style 文档 中查看。
若是是 json 数据导出,须要对表头名和字段进行映射;
相关案例:
import XLSX from 'xlsx';
import export2Excel from '@/assets/utils/export2Excel';
// json 格式
let jsonTable = [{
"sheet1id": 1,
"表头1": "数据11",
"表头2": "数据12",
"表头3": "数据13",
"表头4": "数据14"
}, {
"sheet1id": 2,
"表头1": "数据21",
"表头2": "数据22",
"表头3": "数据23",
"表头4": "数据24"
}];
// 二维数组格式
let aoa = [
['sheet2id', '表头1', '表头2', '表头3', '表头4'],
[1, '数据11', '数据12', '数据13', '数据14'],
[2, '数据21', '数据22', '数据23', '数据24']
]
function handleExportExcel () {
// 使用 XLSX 内置的工具库将 json 转换成 sheet
let worksheet1 = XLSX.utils.json_to_sheet(jsonTable);
// 使用 XLSX 内置的工具库将 aoa 转换成 sheet
let worksheet2 = XLSX.utils.aoa_to_sheet(aoa);
// 设置 excel 表格样式
worksheet1["B1"].s = {
font: {
sz: 14,
bold: true,
color: {
rgb: "FFFFAA00"
}
},
fill: {
bgColor: {
indexed: 64
},
fgColor: {
rgb: "FFFF00"
}
}
};
// 单元格合并
worksheet1["!merges"] = [{
s: { c: 1, r: 0 },
e: { c: 4, r: 0 }
}];
export2Excel({
worksheets: {
sheet1: worksheet1,
sheet2: worksheet2
}, // 导出excel的数据,key表示工做表名,value表示对应工做表的 sheet 数据,支持导出多个工做表
fileName: '个人excel', // 导出文件名
type: 'xlsx' // 文件导出类型
});
}
复制代码