我正在使用此功能
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))
}
})()
以下是示例:
http://jsfiddle.net/insin/cmewv/
在该示例中,他们更改了工作表的名称,但有没有办法更改文件的名称?
答案 0 :(得分:3)
请参阅:Is there any way to specify a suggested filename when using data: URI?
上的答案基本上,使用JavaScript无法做到这一点。如果使用<a>
链接下载文件,您可以使用download
属性指定文件名,但this is not widely supported(现在只是Chrome和BB10)。
答案 1 :(得分:2)
这对我有用:
$scope.exportData = (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))
var link = document.createElement("a");
link.download = "filename.xls";
link.href = uri + base64(format(template, ctx));
link.click();
}
})()
答案 2 :(得分:2)
也适合我。我添加了一个动态下载名称的提示
var ctx = {worksheet: name || 'Worksheet', table: table.innerHTML}
//window.location.href = uri + base64(format(template, ctx))
var downloadName = prompt("write some explanation", "table");
var link = document.createElement("a");
link.download = downloadName + ".xls";
link.href = uri + base64(format(template, ctx));
link.click();