【发布时间】:2016-09-25 19:14:55
【问题描述】:
这是我的函数,可以将我的 html 表格转换为 excel 文件。问题是,我需要将该 excel 文件保存为 .xlsx 但我做不到。有人帮忙吗?
function exceller() {
var uri = 'data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;content-disposition:attachment;base64,'
, template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel"><head><!--[if gte mso 9]><?xml version="1.0" encoding="UTF-8" standalone="yes"?><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]; }) }
$('#toExcel').html($('#pztable').html());
var toExcel = $('#toExcel').html();
var ctx = {
worksheet: name || '',
table: toExcel
};
var link = document.createElement("a");
link.download = "export.xlsx";
link.href = uri + base64(format(template, ctx))
link.click();
link.remove();
}
这里是 jsFiddle:https://jsfiddle.net/jxz60kqj/
【问题讨论】:
-
我没有仔细阅读。你为什么要手动点击那个链接?
-
你也可以提供一下你的作品吗?
-
这是一个角度项目,我的表格数据非常复杂。但我会尝试将其导出到 jsfiddle。我也尝试了窗口定位功能。它也没有用.. @TMB
-
我很担心最后两行,为什么它们是必要的?在我下面的回答中,用户必须单击链接才能下载。
-
没关系。您可以删除最后 5 行并添加它,window.location.href = uri + base64(format(template, ctx)) + '.xlsx';这是同样的事情,但它只是不起作用......
标签: javascript html excel html-table xlsx