【问题标题】:JavaScript - export HTML table data into ExcelJavaScript - 将 HTML 表格数据导出到 Excel
【发布时间】:2023-03-27 11:50:01
【问题描述】:


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

如何在单击按钮时将这 2 个表 ID 传递给 JavaScript 函数?现在点击按钮,只有第一个表被导出到 Excel,因为我只传递了'testTable'。我如何能够将多个表例如: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>

请告诉我,如何做到这一点?
谢谢

【问题讨论】:

  • 你不能使用网络服务来解决这个问题。它也可以在没有回发的情况下工作。

标签: javascript html excel export-to-excel


【解决方案1】:

我推荐另一种格式方法。 John Resig 微模板是一个非常好的和简单的工具,可以满足您的需要。 (ejohn microtemplating)

(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 按钮来执行此功能...我尝试使用此 但这不起作用....它在 jsFiddle 上如何工作?如果我在 html 中实现相同的功能,我将无法在单击按钮时获取文件。请让我知道这是否可能。
  • 尝试 并添加点击事件。函数下载(){ tableToExcel(document.getElementsByTagName("table"), "one"); } var btn = document.getElementById("btn"); btn.addEventListener("点击",下载); jsfiddle.net/Scipion/P8rpn/3
  • 嘿,文件正在下载为“download.xls”;如何更改下载文件的名称?
  • 在 chrome 中是默认名称。要使用其他名称,您可以使用第三方解决方案 stackoverflow.com/questions/13912198/…
  • @Scipion 我已经在here 中尝试过您的代码,我可以成功地将其导出到 excel 文件中,但表格后面显示了一些不必要的字符。看到这个image
【解决方案2】:

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

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

【讨论】:

  • 如何传递多个 tableID?
【解决方案3】:
  1. 为每个表添加一个复选框。使用 javascript 处理已检查的内容。
  2. 如果您只想转换每个表格,可以使用$('table').each(function() { do something })

【讨论】:

    猜你喜欢
    • 2014-06-20
    • 1970-01-01
    • 2015-08-05
    • 2013-06-13
    • 2011-09-27
    • 1970-01-01
    • 1970-01-01
    • 2013-03-11
    • 2016-05-15
    相关资源
    最近更新 更多