28人参与 • 2025-02-14 • Javascript
开发中可能会有这样的需求,本地自己生成了一个表格,此时表格并没有上传到后台服务器上,所以无法通过接口进行下载,此时就需要前端自行处理了。
npm i xlsx npm i file-saver
// index.vue文件 import filesaver from "file-saver" import xlsx from "xlsx"
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; }
<table border="1" cellspacing="0" id="table-parent" > <thead> <tr> <th ></th> </tr> </thead> <tbody> <tr > <td></td> </tr> </tbody> </table>
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)); } })();
tabletoexcel(document.getelementbyid("table-parent"), "导出表格");
到此这篇关于前端直接导出excel文件的两种方式的文章就介绍到这了,更多相关前端导出excel文件内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
您想发表意见!!点此发布评论
版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。
发表评论