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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15224002/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 06:09:24  来源:igfitidea点击:

JavaScript - export HTML table data into Excel

javascripthtmlexcelexport-to-excel

提问by shockwave


I'm trying to convert HTML tables to Excel, i have tried with a JavaScript function which converts a simple table to Excel, it is working fine. If I have multiple tables how will I be able to add all the table data into the Excel file. here's what I tried. I've created 2 tables and given table index testTableand testTable1.


我正在尝试将 HTML 表转换为 Excel,我尝试使用 JavaScript 函数将简单的表转换为 Excel,它工作正常。如果我有多个表格,我将如何将所有表格数据添加到 Excel 文件中。这是我尝试过的。我创建了 2 个表并给出了表索引testTabletestTable1.

How will i pass these 2 table ids to the JavaScript function on click of the button? right now on click of the button only the first table is exported to Excel as I'm passing only 'testTable'. how will i be able to export multiple tables eg: testTable, testTable1into Excel?

我将如何在单击按钮时将这 2 个表 ID 传递给 JavaScript 函数?现在点击按钮,只有第一个表被导出到 Excel,因为我只是通过'testTable'。我将如何能够导出多个表,例如:testTabletestTable1到 Excel 中?

Here's the JavaScript:

这是 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>

Here's the HTML part,

这是 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>

Please let me know, how this can be done?
Thanks

请让我知道,如何做到这一点?
谢谢

采纳答案by Scipion

I recommend another Format method. the John Resig micro-template is a very good and simple tool for do what you need. (ejohn microtemplating)

我推荐另一种格式方法。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, "\r")
              .replace(/\t=(.*?)}}/g, "',,'")
              .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;
  };
})();

It is very simple to use. This allows not only show variables between HTML but also execute JavaScript code

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

Your template string need some modification to work with this microtemplate.

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

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

finally only need to select all the tables that appear in your example

最后只需要选择您的示例中出现的所有表

document.getElementsByTagName("table");

you can see how it works http://jsfiddle.net/Scipion/P8rpn/1/

你可以看到它是如何工作的http://jsfiddle.net/Scipion/P8rpn/1/

回答by gongzhitaao

  1. Add a checkbox for each table. Use javascript to process those that are checked.
  2. In case if you just want to convert every table, you could use $('table').each(function() { do something }).
  1. 为每个表添加一个复选框。使用 javascript 处理那些被检查的。
  2. 如果您只想转换每个表,则可以使用$('table').each(function() { do something }).

回答by divyabharathi

create a function and pass the tableID to it

创建一个函数并将 tableID 传递给它

 function passing_id_to_excel(tableID){ 
  var myTableid =
 document.getElementById(tableID) //remaining code }