将HTML表格导出到Excel,但为文件select一个名称

我正在使用这个function

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/

在这个例子中,他们改变工作表的名字,但是有没有办法改变文件的名字?

查看答案: 有没有什么办法可以在使用data:URI时指定一个build议的文件名?

基本上,没有办法用JavaScript来做到这一点。 如果使用<a>链接下载文件,可以使用download属性指定一个文件名,但这并不被广泛支持 (现在只是Chrome和BB10)。

这适用于我:

  $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(); } })() 

也适用于我。 我添加一个提示来dynamic地下载名称

  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();