Julia
Julia

Reputation: 1399

Javascript export multiple html tables to an excel file

I have a html page with multiple tables, I want to export these tables to a single excel file in a single sheet. How can I do that. I tried the following code, and it works fine with 1 table. How do I modify the code to export multiple tables?

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>

Upvotes: 1

Views: 2636

Answers (1)

jordiburgos
jordiburgos

Reputation: 6302

You could use ExcellentExport.js library. It helps to create an XLS, XLSX or CSV file in the client side (browser) getting data from an HTML table or a JavaScript array.

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

Sample code:

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

The array parameter contains the sheet list. The first element refers to testTable and the second element to testTable2.

Note: I am the developer of ExcellentExport.js

Upvotes: 1

Related Questions