【问题标题】:exporting html table to xls not working using jquery将html表导出到xls不使用jquery
【发布时间】:2014-07-10 16:10:21
【问题描述】:
 <script>
 $(document).ready(function(){
 $("#btnExport").click(function(e) {

  window.open('data:application/vnd.ms-excel,' + $('#dvDatatable').html());
  e.preventDefault();
  });
  });
 </script>

这是我用来导出我的 html 表的代码,其中 #btnExport 是我的导出按钮 '#dvDatatable' 是我的表 id。但这段代码对我不起作用。 它只是像简单文件一样下载

我必须对我的代码进行哪些更改?

【问题讨论】:

标签: jquery html jquery-plugins export-to-excel


【解决方案1】:

你可以使用这个功能:

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
            }
            var blob = new Blob([format(template, ctx)]);
            var blobURL = window.URL.createObjectURL(blob);
            return blobURL;
        }
})()

在你的 jquery 中是这样的:

$("#btnExport").click(function () {
    var blobURL = tableToExcel('account_table', 'test_table');
    $(this).attr('download','download.xls')
    $(this).attr('href',blobURL);
});

Example Fiddle

参考资料: Link1 Link2

【讨论】:

  • 这个你好运吗?
  • 这对任何人都有效吗?任何人都可以为上述答案提供完整的 html+js 代码吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-06
  • 1970-01-01
  • 1970-01-01
  • 2013-07-09
  • 2013-07-11
  • 2016-06-30
相关资源
最近更新 更多