JavaScript - 将HTML表格数据导出到Excel

12
我正在尝试将HTML表格转换为Excel,我已经尝试了一个JavaScript函数,可以将简单的表格转换为Excel,它运行良好。如果我有多个表格,如何将所有表格数据添加到Excel文件中?这是我尝试过的。我创建了两个表,并给出了表索引testTabletestTable1
在点击按钮时,我该如何将这两个表格ID传递给JavaScript函数?现在,仅通过传递'testTable',单击按钮时只导出第一个表格到Excel。如何能够导出多个表格,例如:testTabletestTable1 到Excel?
以下是JavaScript代码:
<script>

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

</script>

这是HTML部分,

<table id="testTable">
    <thead>
        <tr>
            <th>Name</th>
            <th>ACP</th>
            <th>OEMCP</th>
            <th>Unix<br>
                NT 3.1</th>
            <th>Unix<br>
                NT 3.51</th>
            <th>Unix<br>
                95</th>
        </tr>
    </thead>
</table>
<table id="testTable1">
    <thead>
        <tr>
            <th>Name</th>
            <th>ACP</th>
            <th>OEMCP</th>
            <th>Windows<br>
                NT 3.1</th>
            <th>Windows<br>
                NT 3.51</th>
            <th>Windows<br>
                95</th>
        </tr>
    </thead>
</table>

请告诉我,如何完成这个任务?
谢谢


你不能使用 Web 服务解决这个问题吗?它也可以在没有 postback 的情况下工作。 - osmanraifgunes
3个回答

9

我建议使用另一种格式方法。John Resig的微型模板是一个非常好用且简单的工具,可以满足您的需求。(ejohn微型模板

(function(){
  var cache = {};

  this.tmpl = function tmpl(str, data){
    // Figure out if we're getting a template, or if we need to
    // load the template - and be sure to cache the result.
    var fn = !/\W/.test(str) ?
      cache[str] = cache[str] ||
        tmpl(document.getElementById(str).innerHTML) :

      // Generate a reusable function that will serve as a template
      // generator (and which will be cached).
      new Function("obj",
        "var p=[],print=function(){p.push.apply(p,arguments);};" +

        // Introduce the data as local variables using with(){}
        "with(obj){p.push('" +

        // Convert the template into pure JavaScript
        str.replace(/[\r\t\n]/g, " ")
              .split("{{").join("\t")
              .replace(/((^|}})[^\t]*)'/g, "$1\r")
              .replace(/\t=(.*?)}}/g, "',$1,'")
              .split("\t").join("');")
              .split("}}").join("p.push('")
              .split("\r").join("\\'")
              + "');}return p.join('');");

    // Provide some basic currying to the user
    return data ? fn( data ) : fn;
  };
})();

使用非常简单。这不仅允许在HTML之间显示变量,还可以执行JavaScript代码。

您的模板字符串需要进行一些修改才能与此微型模板一起使用。

{{for(var i=0; i<tables.length;i++){ }}
    <table>
        {{=tables[i]}}
    </table>
{{ } }}

最终只需选择您示例中出现的所有表格。
document.getElementsByTagName("table");

您可以查看它的工作原理http://jsfiddle.net/Scipion/P8rpn/1/


非常感谢您,Scipion!我只是想知道是否可以在单击HTML按钮时执行此功能...我尝试了以下代码: <input type="button" onclick="tableToExcel(document.getElementsByTagName("table"),"one")" value="Export to Excel"> 但这不起作用....它在jsFiddle上是如何工作的?如果我在HTML中实现相同的功能,我无法在单击按钮时获取文件。请告诉我这是否可能。 - shockwave
1
尝试使用<button id="btn">下载</button>并添加点击事件。函数download(){ tableToExcel(document.getElementsByTagName("table"), "one"); } var btn = document.getElementById("btn"); btn.addEventListener("click",download); http://jsfiddle.net/Scipion/P8rpn/3/ - Scipion
嘿,文件正在以“download.xls”下载;我如何更改下载文件的名称? - shockwave
在Chrome中是默认名称。如果要使用其他名称,可以使用第三方解决方案https://dev59.com/yWzXa4cB1Zd3GeqPQirq#13931279 - Scipion
@Scipion 我已经在这里尝试了你的代码,我可以成功地将它导出到Excel文件中,但是表格后面显示了一些不必要的字符。请看这张image - user3771102

0
  1. 为每个表格添加一个复选框。使用JavaScript来处理已勾选的内容。
  2. 如果您只想转换每个表格,可以使用$('table').each(function(){ do something })

0
创建一个函数并将tableID传递给它。
 function passing_id_to_excel(tableID){ 
  var myTableid =
 document.getElementById(tableID) //remaining code }

我该如何传递多个tableIDs? - shockwave

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接