前端直接導出excel文件的兩種方式
更新時間:2025年01月06日 08:31:36 作者:庫庫的寫代碼
這篇文章主要介紹了兩種方法在前端實現(xiàn)本地表格導出功能,分別是插件方式和本地直接導出,文中通過代碼介紹的非常詳細,需要的朋友可以參考下
前言
開發(fā)中可能會有這樣的需求,本地自己生成了一個表格,此時表格并沒有上傳到后臺服務(wù)器上,所以無法通過接口進行下載,此時就需要前端自行處理了。
一、插件方式
1.插件安裝
npm i xlsx npm i file-saver
2.引入
// index.vue文件 import FileSaver from "file-saver" import XLSX from "xlsx"
3.導出
exportExcel() {
let et = XLSX.utils.table_to_book(
//獲取table的DOM
document.getElementById('table-contents')
);
let etout = XLSX.write(et, {
bookType: 'xlsx',
bookSST: true,
type: 'array'
});
try {
FileSaver.saveAs(
new Blob([etout], {
type: 'application/octet-stream'
}),
'XXX.xls'
);
} catch (e) {
//console.log(e, etout)
}
console.log(etout);
return etout;
}
二、本地直接導出
1.頁面規(guī)則
- 頁面必須要有table表格
<table border="1" cellspacing="0" id="table-parent" >
<thead>
<tr>
<th ></th>
</tr>
</thead>
<tbody>
<tr >
<td></td>
</tr>
</tbody>
</table>
2.在JS中添加函數(shù)
var tableToExcel = (function() {
var uri = 'data:application/vnd.ms-excel;base64,',
template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>',
base64 = function(s) {
return window.btoa(unescape(encodeURIComponent(s)))
},
format = function(s, c) {
return s.replace(/{(\w+)}/g, function(m, p) {
return c[p];
})
}
return function(table, name) {
if (!table.nodeType) table = document.getElementById(table);
var ctx = {
worksheet: name || 'Worksheet',
table: table.innerHTML
};
window.location.href = uri + base64(format(template, ctx));
}
})();3.調(diào)用
tableToExcel(document.getElementById("table-parent"), "導出表格");總結(jié)
到此這篇關(guān)于前端直接導出excel文件的兩種方式的文章就介紹到這了,更多相關(guān)前端導出excel文件內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
javascript設(shè)置金額樣式轉(zhuǎn)換保留兩位小數(shù)示例代碼
本文為大家介紹下javascript設(shè)置金額樣式即保留兩位小數(shù),下面有個不錯的教程,需要的朋友可以了解下2013-12-12
微信小程序開發(fā)之a(chǎn)nimation循環(huán)動畫實現(xiàn)的讓云朵飄效果
這篇文章主要介紹了微信小程序開發(fā)之a(chǎn)nimation循環(huán)動畫實現(xiàn)的讓云朵飄效果,結(jié)合實例形式分析了animation結(jié)合js時間函數(shù)實現(xiàn)循環(huán)動畫效果的具體步驟與相關(guān)操作技巧,需要的朋友可以參考下2017-07-07
JavaScript實現(xiàn)當網(wǎng)頁加載完成后執(zhí)行指定函數(shù)的方法
這篇文章主要介紹了JavaScript實現(xiàn)當網(wǎng)頁加載完成后執(zhí)行指定函數(shù)的方法,實例分析了javascript加載頁面及執(zhí)行函數(shù)的技巧,需要的朋友可以參考下2015-03-03

