7

我正在使用这个功能

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/

在该示例中,他们更改了工作表的名称,但是有没有办法更改文件的名称?

4

3 回答 3

3

请参阅以下位置的答案:使用数据时是否有任何方法可以指定建议的文件名:URI?

基本上,没有办法用 JavaScript 做到这一点。如果通过链接下载文件,您可以使用该属性<a>指定文件名,但这并未得到广泛支持(目前只有 Chrome 和 BB10)。download

于 2013-01-02T17:03:26.457 回答
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();
              }
            })()
于 2015-10-07T11:49:01.373 回答
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();
于 2015-11-30T10:07:17.830 回答