前言
开发中可能会有这样的需求,本地自己生成了一个表格,此时表格并没有上传到后台服务器上,所以无法通过接口进行下载,此时就需要前端自行处理了。
一、插件方式
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.页面规则
- 页面必须要有table表格
<table border="1" cellspacing="0" id="table-parent" > <thead> <tr> <th ></th> </tr> </thead> <tbody> <tr > <td></td> </tr> </tbody> </table>
2.在JS中添加函数
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.调用
tableToExcel(document.getElementById("table-parent"), "导出表格");
总结
到此这篇关于前端直接导出excel文件的两种方式的文章就介绍到这了,更多相关前端导出excel文件内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
来源链接:https://www.jb51.net/javascript/333650xyu.htm
© 版权声明
本站所有资源来自于网络,仅供学习与参考,请勿用于商业用途,否则产生的一切后果将由您(转载者)自己承担!
如有侵犯您的版权,请及时联系3500663466#qq.com(#换@),我们将第一时间删除本站数据。
如有侵犯您的版权,请及时联系3500663466#qq.com(#换@),我们将第一时间删除本站数据。
THE END
暂无评论内容