【问题标题】:Javascript export multiple html tables to an excel fileJavascript将多个html表导出到一个excel文件
【发布时间】:2020-11-23 01:05:17
【问题描述】:

我有一个包含多个表格的 html 页面,我想将这些表格导出到单个工作表中的单个 Excel 文件中。我怎样才能做到这一点。我尝试了以下代码,它适用于 1 个表。如何修改代码导出多个表?

var tableToExcel = () => {
  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))
  }
}
<table id="testTable">
  <tr>
    <td>a</td>
    <td>aaa</td>
    <td>aaaaaa</td>
  </tr>
  <tr>
    <td>b</td>
    <td>bbb</td>
    <td>bbbbbb</td>
  </tr>
</table>

<table id="testTable2">
  <tr>
    <td>222a</td>
    <td>222aaa</td>
    <td>222aaaaaa</td>
  </tr>
  <tr>
    <td>222b</td>
    <td>22bbb</td>
    <td>222bbbbbb</td>
  </tr>
</table>

<button onclick="tableToExcel('testTable', 'W3C Example Table')">Export</button>

【问题讨论】:

  • 听起来你想在 R 或 Python 中使用网络抓取库。

标签: javascript html excel export-to-excel


【解决方案1】:

您可以使用ExcellentExport.js 库。它有助于在客户端(浏览器)中创建 XLS、XLSX 或 CSV 文件,从 HTML 表或 JavaScript 数组中获取数据。

https://github.com/jmaister/excellentexport/

示例代码:

<script>
function export() {
    return ExcellentExport.convert({ anchor: this, filename: 'data_123.array', format: 'xlsx'}, [
        {name: 'Sheet Name Here 1', from: {table: 'testTable'}},
        {name: 'Sheet Name Here 2', from: {table: 'testTable2'}}
    ]);
}
</script>
<a download="somedata.xlsx" href="#" onclick="return export();">Export to XLSX</a>

数组参数包含工作表列表。第一个元素引用 testTable,第二个元素引用 testTable2

注意:我是ExcellentExport.js的开发者

【讨论】:

    猜你喜欢
    • 2016-12-06
    • 2023-03-21
    • 1970-01-01
    • 1970-01-01
    • 2014-08-29
    • 2015-06-23
    • 2016-02-28
    • 2013-06-13
    • 1970-01-01
    相关资源
    最近更新 更多