前端實(shí)現(xiàn)導(dǎo)出excel表格的方式有好幾種,最近公司有一個(gè)項(xiàng)目要用到這個(gè)功能,最開始百度查到的一些例子導(dǎo)出數(shù)據(jù)都限制在1.5M大小。最終還是在github上面找到了答案。
<html>
<head>
<meta charset="utf-8">
<title>js導(dǎo)出excel</title>
<script src="js/FileSaver.js"></script>
<script>
// https://github.com/eligrey/FileSaver.js
function onDocumentLoad() {
document.getElementById("export").addEventListener('click',function(){
var blob = new Blob([document.getElementsByClassName("exportTable")[0].outerHTML], {
type: "text/plain;charset=utf-8"
});
saveAs(blob, "export.xls");
})
}
document.addEventListener('DOMContentLoaded', onDocumentLoad);
</script>
</head>
<body>
<button id="export">導(dǎo)出excel</button><br>
<table class="exportTable">
這里使用了GitHub上面的找到的一個(gè)FileSaver插件,先使用獲取表格table的HTML代碼(document.getElementsByClassName("exportTable")[0].outerHTML就是獲取到的HTML代碼及文本內(nèi)容),
用前端自帶的new Blob構(gòu)造函數(shù)生成數(shù)據(jù)對象,這里注意type的定義,GitHub上面的type定義我使用時(shí)是亂碼的;
生成的數(shù)據(jù)對象blob傳給FileSaver插件的saveAs方法,"export.xls"是下載時(shí)的文件名稱和格式。這樣就實(shí)現(xiàn)了導(dǎo)出excel表格了。
原demo地址:https://github.com/kebingzao/fileSaver_excel
注意:原demo的Blob的type屬性定義導(dǎo)出的excel文件中的中文文本是亂碼的??!
npm包使用方式:
1、安裝
npm install file-saver --save
2、require引用
var FileSaver = require('file-saver');
var blob = new Blob(["Hello, world!"], {type: "text/plain;charset=utf-8"});
FileSaver.saveAs(blob, "hello world.txt");