前端直接導(dǎo)出excel文件的兩種方式
前言
開發(fā)中可能會(huì)有這樣的需求,本地自己生成了一個(gè)表格,此時(shí)表格并沒有上傳到后臺(tái)服務(wù)器上,所以無法通過接口進(jìn)行下載,此時(shí)就需要前端自行處理了。
一、插件方式
1.插件安裝
npm i xlsx npm i file-saver
2.引入
// index.vue文件 import FileSaver from "file-saver" import XLSX from "xlsx"
3.導(dǎo)出
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;
}
二、本地直接導(dǎo)出
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"), "導(dǎo)出表格");總結(jié)
到此這篇關(guān)于前端直接導(dǎo)出excel文件的兩種方式的文章就介紹到這了,更多相關(guān)前端導(dǎo)出excel文件內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
javascript設(shè)置金額樣式轉(zhuǎn)換保留兩位小數(shù)示例代碼
本文為大家介紹下javascript設(shè)置金額樣式即保留兩位小數(shù),下面有個(gè)不錯(cuò)的教程,需要的朋友可以了解下2013-12-12
微信小程序開發(fā)之a(chǎn)nimation循環(huán)動(dòng)畫實(shí)現(xiàn)的讓云朵飄效果
這篇文章主要介紹了微信小程序開發(fā)之a(chǎn)nimation循環(huán)動(dòng)畫實(shí)現(xiàn)的讓云朵飄效果,結(jié)合實(shí)例形式分析了animation結(jié)合js時(shí)間函數(shù)實(shí)現(xiàn)循環(huán)動(dòng)畫效果的具體步驟與相關(guān)操作技巧,需要的朋友可以參考下2017-07-07
JavaScript實(shí)現(xiàn)當(dāng)網(wǎng)頁加載完成后執(zhí)行指定函數(shù)的方法
這篇文章主要介紹了JavaScript實(shí)現(xiàn)當(dāng)網(wǎng)頁加載完成后執(zhí)行指定函數(shù)的方法,實(shí)例分析了javascript加載頁面及執(zhí)行函數(shù)的技巧,需要的朋友可以參考下2015-03-03
javascript刪除數(shù)組元素的七個(gè)方法示例
這篇文章主要給大家介紹了關(guān)于javascript刪除數(shù)組元素的七個(gè)方法,文中通過示例代碼介紹的非常詳細(xì),對大家學(xué)習(xí)或者使用javascript具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧2019-09-09
JavaScript文本特效實(shí)例小結(jié)【3個(gè)示例】
這篇文章主要介紹了JavaScript文本特效,結(jié)合3個(gè)實(shí)例分析了javascript基于定時(shí)器的文字動(dòng)態(tài)操作特效相關(guān)實(shí)現(xiàn)技巧,需要的朋友可以參考下2018-12-12

