Vue前端導(dǎo)出Excel文件的詳細(xì)實(shí)現(xiàn)方案
一、技術(shù)選型
1.使用 vue-json-excel 插件實(shí)現(xiàn)
優(yōu)點(diǎn):簡單便捷,易上手,開箱即用;
缺點(diǎn):不支持 excel 表格樣式設(shè)置,且支持功能比較單一;
2.基于 sheetJS-xlsx 解析器的 xlsx-style 實(shí)現(xiàn)(推薦)
優(yōu)點(diǎn):支持格式眾多,支持 excel 表格樣式設(shè)置,功能強(qiáng)大,可控性高,可讀取和導(dǎo)出excel;
缺點(diǎn):使用較為復(fù)雜,上手成本較大,且高級功能需要收費(fèi),但該功能可以借助 xlsx-style 實(shí)現(xiàn);
二、技術(shù)實(shí)現(xiàn)
使用 vue-json-excel 插件實(shí)現(xiàn)
1.安裝 vue-json-excel 依賴
npm install -S vue-json-excel
2.注冊插件到 vue 實(shí)例
import Vue from "vue";
import JsonExcel from "vue-json-excel";
Vue.component("downloadExcel", JsonExcel);
3.使用方式
在需要觸發(fā)導(dǎo)出事件的外出包裹 download-excel 組件
該組件支持的屬性可參考vue-json-excel 的 github 文檔
<download-excel :data="json_data"> Download Data <img src="download_icon.png" /> </download-excel>
首先需要處理導(dǎo)出到 excel 文件的數(shù)據(jù)內(nèi)容,分別是以下數(shù)據(jù):
- 表頭名數(shù)據(jù) json_fields:可以選擇要導(dǎo)出的字段,并為字段分配標(biāo)簽。該數(shù)據(jù)類型為 Object ,key 對應(yīng)的是標(biāo)簽,value 對應(yīng)的是 JSON 字段,將導(dǎo)出與數(shù)據(jù)列表相同字段的數(shù)據(jù)。如果需要自定義導(dǎo)出的數(shù)據(jù),可以定義回調(diào)函數(shù)。
- 表格數(shù)據(jù) json_data:該數(shù)據(jù)類型為 Array,存儲了需要導(dǎo)出的數(shù)據(jù)內(nèi)容;
let json_fields = {
// fieldLabel(表頭名),attributeName(對應(yīng)字段名)
fieldLabel: attributeName,
// 使用回調(diào)自定義導(dǎo)出數(shù)據(jù)
anotherFieldLabel: {
field: anotherAttributeName,
callback: (value) => {
return `formatted value ${value}`;
},
},
};
let json_data = [
{
attributeName: value1,
anotherAttributeName: value2
},
{
attributeName: value3,
anotherAttributeName: value4
}
];
處理完數(shù)據(jù)之后則可以將數(shù)據(jù)傳入 download-excel 組件中,該組件沒有任何樣式,只需要設(shè)置內(nèi)部包裹的元素樣式即可;
<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>
然而在實(shí)際的業(yè)務(wù)場景下,導(dǎo)出表格數(shù)據(jù)通常是導(dǎo)出表格的所有數(shù)據(jù),所以在導(dǎo)出的過程中,需要調(diào)用請求接口去獲取表格中的所有數(shù)據(jù),而調(diào)用接口獲取數(shù)據(jù)是異步執(zhí)行的過程,該插件也針對這個場景提供了解決方案。
相關(guān)案例:
<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>
基于 sheetJS-xlsx 解析器的 xlsx-style 實(shí)現(xiàn)(推薦)
由于這部分涉及內(nèi)容較多,后續(xù)有需要會封裝該功能
這里只對封裝的 export2Excel 使用方法進(jìn)行說明,暫時不對原理進(jìn)行講解。
該插件不僅支持 excel 文件的導(dǎo)出,也支持文件導(dǎo)入功能,并且導(dǎo)出 excel 文件的不僅支持 json 數(shù)據(jù),也支持 table 導(dǎo)出;
由于 sheetjs-xlsx 提供的工具庫其高級功能是付費(fèi)項(xiàng)目,如修改表格樣式等功能,因此選用了基于 sheetjs-xlsx 實(shí)現(xiàn)的 xlsx-style 插件。
兼容性:

1.安裝依賴
npm install -S xlsx npm install -S xlsx-style
而 xlsx-style 插件在使用的時候會報(bào)錯,官方也對該問題給出了解決方案,就是在根目錄下的vue.config.js配置文件添加如下代碼:
module.exports = {
configureWebpack: {
externals: {
'./cptable': 'var cptable'
}
}
}
還有一種方案是改源代碼,但不推薦使用,就不做說明了。
2.使用方法
這里封裝了導(dǎo)出 excel 文件的方法,其中,文件下載的功能有兩個方案實(shí)現(xiàn),分別是:
- 通過 a 標(biāo)簽的文件下載功能,利用 URL.createObjectURL 方法生成下載鏈接實(shí)現(xiàn);(本文使用的方法)
- 通過第三方插件 file-saver 插件實(shí)現(xiàn)文件下載功能;
js-xlsx 插件自帶了相關(guān)的函數(shù)去方便實(shí)現(xiàn)不同數(shù)據(jù)格式的轉(zhuǎn)換:
- 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 函數(shù)具體代碼,只需要將代碼復(fù)制到創(chuàng)建的 export2Excel.js 文件中即可:
/**
* create by lwj
* @file 導(dǎo)出export插件封裝
*/
import * as styleXLSX from 'xlsx-style'
/**
* 將 String 轉(zhuǎn)換成 ArrayBuffer
* @method 類型轉(zhuǎn)換
* @param {String} [s] wordBook內(nèi)容
* @return {Array} 二進(jìn)制流數(shù)組
*/
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) {
// 轉(zhuǎn)換成二進(jìn)制流
buf[i] = s.charCodeAt(i) & 0xFF;
}
return buf;
}
/**
* 方案一:利用 URL.createObjectURL 下載 (以下選用)
* 方案二:通過 file-saver 插件實(shí)現(xiàn)文件下載
* @method 文件下載
* @param {Object} [obj] 導(dǎo)出內(nèi)容 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); // 創(chuàng)建blob地址
}
aLink.download = fileName;
aLink.click();
setTimeout(function () {
URL.revokeObjectURL(obj);
}, 100);
}
/**
* @method 數(shù)據(jù)導(dǎo)出excel
* @param {Object} [worksheets] 工作表數(shù)據(jù)內(nèi)容
* @param {String} [fileName='ExcelFile'] 導(dǎo)出excel文件名
* @param {String} [type='xlsx'] 導(dǎo)出文件類型
*/
export default function export2Excel ({
worksheets,
fileName = 'ExcelFile',
type = 'xlsx'
} = {}) {
let sheetNames = Object.keys(worksheets);
let workbook = {
SheetNames: sheetNames, //保存的工作表名
Sheets: worksheets
};
// excel的配置項(xiàng)
let wopts = {
bookType: type, // 生成的文件類型
bookSST: false, // 是否生成Shared String Table,官方解釋是,如果開啟生成速度會下降,但在低版本IOS設(shè)備上有更好的兼容性
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);
}
需要注意幾個問題:
- xlsx 和 xlsx-style 的默認(rèn)導(dǎo)出函數(shù)名都是 XLSX ,如果同時導(dǎo)入的話,需要注意設(shè)置別名,避免函數(shù)覆蓋出現(xiàn)問題;
- 如果不想使用 xlsx 插件,只使用 xlsx-style 插件同樣也是可以的,只是要自己將需要導(dǎo)出的數(shù)據(jù)轉(zhuǎn)換成 worksheet 格式對象,其原理也就是將導(dǎo)出數(shù)據(jù)轉(zhuǎn)換成 worksheet 規(guī)定的數(shù)據(jù)格式,具體可以查看js-xlsx 文檔說明;(可以自己嘗試實(shí)現(xiàn))
然后只需要在需要導(dǎo)出 excel 的地方調(diào)用即可,如果對導(dǎo)出表格樣式有要求的情況下,可以去了解如何配置表格樣式,具體配置方法可以去xlsx-style 文檔 中查看。
如果是 json 數(shù)據(jù)導(dǎo)出,需要對表頭名和字段進(jìn)行映射;
相關(guān)案例:
import XLSX from 'xlsx';
import export2Excel from '@/assets/utils/export2Excel';
// json 格式
let jsonTable = [{
"sheet1id": 1,
"表頭1": "數(shù)據(jù)11",
"表頭2": "數(shù)據(jù)12",
"表頭3": "數(shù)據(jù)13",
"表頭4": "數(shù)據(jù)14"
}, {
"sheet1id": 2,
"表頭1": "數(shù)據(jù)21",
"表頭2": "數(shù)據(jù)22",
"表頭3": "數(shù)據(jù)23",
"表頭4": "數(shù)據(jù)24"
}];
// 二維數(shù)組格式
let aoa = [
['sheet2id', '表頭1', '表頭2', '表頭3', '表頭4'],
[1, '數(shù)據(jù)11', '數(shù)據(jù)12', '數(shù)據(jù)13', '數(shù)據(jù)14'],
[2, '數(shù)據(jù)21', '數(shù)據(jù)22', '數(shù)據(jù)23', '數(shù)據(jù)24']
]
function handleExportExcel () {
// 使用 XLSX 內(nèi)置的工具庫將 json 轉(zhuǎn)換成 sheet
let worksheet1 = XLSX.utils.json_to_sheet(jsonTable);
// 使用 XLSX 內(nèi)置的工具庫將 aoa 轉(zhuǎn)換成 sheet
let worksheet2 = XLSX.utils.aoa_to_sheet(aoa);
// 設(shè)置 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
}, // 導(dǎo)出excel的數(shù)據(jù),key表示工作表名,value表示對應(yīng)工作表的 sheet 數(shù)據(jù),支持導(dǎo)出多個工作表
fileName: '我的excel', // 導(dǎo)出文件名
type: 'xlsx' // 文件導(dǎo)出類型
});
}
三、參考資料
總結(jié)
到此這篇關(guān)于Vue前端導(dǎo)出Excel文件的文章就介紹到這了,更多相關(guān)Vue導(dǎo)出Excel文件內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Vue 實(shí)現(xiàn)復(fù)制功能,不需要任何結(jié)構(gòu)內(nèi)容直接復(fù)制方式
今天小編就為大家分享一篇Vue 實(shí)現(xiàn)復(fù)制功能,不需要任何結(jié)構(gòu)內(nèi)容直接復(fù)制方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-11-11
vue發(fā)送驗(yàn)證碼計(jì)時器防止刷新實(shí)現(xiàn)詳解
這篇文章主要為大家介紹了vue發(fā)送驗(yàn)證碼計(jì)時器防止刷新實(shí)現(xiàn)詳解,<BR>有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-03-03
基于Vue3實(shí)現(xiàn)數(shù)字華容道游戲的示例代碼
這篇文章主要為大家詳細(xì)介紹了如何利用Vue編寫一個數(shù)字華容道游戲,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-04-04

