【问题标题】:How to export html tables to excel in multi tab format?如何以多标签格式将 html 表格导出为 excel?
【发布时间】:2018-05-24 20:21:54
【问题描述】:

我有一个将 html 表导出到 excel 文件的代码。但现在我必须在单个 excel 文件的多个选项卡中导出 html 表。这是我的代码供参考。 在这段代码中,我有三个不同的表。一旦我单击“导出到 Excel”。将下载 Excel。现在在 excel 文件中有一个选项卡,但现在我希望 excel 文件应该包含多个选项卡。每个选项卡应包含不同的表记录。

<script type="text/javascript">
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]--><meta http-equiv="content-type" content="text/plain; charset=UTF-8"/></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>

<input type="button" onclick="tableToExcel('testTable', 'W3C Example Table')" value="Export to Excel">
<br><br>


<p>Table 1</p>
<table id="testTable" border="1">
  <thead>
    <tr>
      <th>Num1</th>
      <th>Num2</th>
      <th>Num3</th>
      <th>Num4</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>11</td>
      <td>12</td>
      <td>13</td>
      <td>14</td>
    </tr>
    <tr>
      <td>21</td>
      <td>22</td>
      <td>23</td>
      <td>24</td>
    </tr>
    <tr>
      <td>31</td>
      <td>32</td>
      <td>33</td>
      <td>34</td>
    </tr>
    <tr>
      <td>41</td>
      <td>42</td>
      <td>43</td>
      <td>44</td>
    </tr>
  </tbody>
</table>


<p>Table 2</p>
<table id="" border="1">
  <thead>
    <tr>
      <th>Alpha1</th>
      <th>Alpha2</th>
      <th>Alpha3</th>
      <th>Alpha4</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>a</td>
      <td>b</td>
      <td>c</td>
      <td>d</td>
    </tr>
    <tr>
      <td>e</td>
      <td>f</td>
      <td>g</td>
      <td>h</td>
    </tr>
    <tr>
      <td>i</td>
      <td>j</td>
      <td>k</td>
      <td>l</td>
    </tr>
    <tr>
      <td>m</td>
      <td>n</td>
      <td>o</td>
      <td>p</td>
    </tr>
  </tbody>
</table>

<p>Table 3</p>
<table id="" border="1">
  <thead>
    <tr>
      <th>Fruit1</th>
      <th>Fruit2</th>
      <th>Fruit3</th>
      <th>Fruit4</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>apple</td>
      <td>apple</td>
      <td>apple</td>
      <td>apple</td>
    </tr>
    <tr>
      <td>orange</td>
      <td>orange</td>
      <td>orange</td>
      <td>orange</td>
    </tr>
    <tr>
      <td>mango</td>
      <td>mango</td>
      <td>mango</td>
      <td>mango</td>
    </tr>
    <tr>
      <td>graphs</td>
      <td>graphs</td>
      <td>graphs</td>
      <td>graphs</td>
    </tr>
  </tbody>
</table>

【问题讨论】:

  • 您需要使用 PHPExcel 等可用于创建原生格式文件的众多库之一来创建原生电子表格格式文件,例如 BIFF (xls) 或 OfficeOpenXML (xlsx)

标签: javascript php jquery html ajax


【解决方案1】:

我认为你需要这个

  var tablesToExcel = (function() {
    var uri = 'data:application/vnd.ms-excel;base64,'
    , tmplWorkbookXML = '<?xml version="1.0"?><?mso-application progid="Excel.Sheet"?><Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet" xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet">'
      + '<DocumentProperties xmlns="urn:schemas-microsoft-com:office:office"><Author>Axel Richter</Author><Created>{created}</Created></DocumentProperties>'
      + '<Styles>'
      + '<Style ss:ID="Currency"><NumberFormat ss:Format="Currency"></NumberFormat></Style>'
      + '<Style ss:ID="Date"><NumberFormat ss:Format="Medium Date"></NumberFormat></Style>'
      + '</Styles>' 
      + '{worksheets}</Workbook>'
    , tmplWorksheetXML = '<Worksheet ss:Name="{nameWS}"><Table>{rows}</Table></Worksheet>'
    , tmplCellXML = '<Cell{attributeStyleID}{attributeFormula}><Data ss:Type="{nameType}">{data}</Data></Cell>'
    , 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(tables, wsnames, wbname, appname) {
      var ctx = "";
      var workbookXML = "";
      var worksheetsXML = "";
      var rowsXML = "";

      for (var i = 0; i < tables.length; i++) {
        if (!tables[i].nodeType) tables[i] = document.getElementById(tables[i]);
        for (var j = 0; j < tables[i].rows.length; j++) {
          rowsXML += '<Row>'
          for (var k = 0; k < tables[i].rows[j].cells.length; k++) {
            var dataType = tables[i].rows[j].cells[k].getAttribute("data-type");
            var dataStyle = tables[i].rows[j].cells[k].getAttribute("data-style");
            var dataValue = tables[i].rows[j].cells[k].getAttribute("data-value");
            dataValue = (dataValue)?dataValue:tables[i].rows[j].cells[k].innerHTML;
            var dataFormula = tables[i].rows[j].cells[k].getAttribute("data-formula");
            dataFormula = (dataFormula)?dataFormula:(appname=='Calc' && dataType=='DateTime')?dataValue:null;
            ctx = {  attributeStyleID: (dataStyle=='Currency' || dataStyle=='Date')?' ss:StyleID="'+dataStyle+'"':''
                   , nameType: (dataType=='Number' || dataType=='DateTime' || dataType=='Boolean' || dataType=='Error')?dataType:'String'
                   , data: (dataFormula)?'':dataValue
                   , attributeFormula: (dataFormula)?' ss:Formula="'+dataFormula+'"':''
                  };
            rowsXML += format(tmplCellXML, ctx);
          }
          rowsXML += '</Row>'
        }
        ctx = {rows: rowsXML, nameWS: wsnames[i] || 'Sheet' + i};
        worksheetsXML += format(tmplWorksheetXML, ctx);
        rowsXML = "";
      }

      ctx = {created: (new Date()).getTime(), worksheets: worksheetsXML};
      workbookXML = format(tmplWorkbookXML, ctx);

//console.log(workbookXML);

      var link = document.createElement("A");
      link.href = uri + base64(workbookXML);
      link.download = wbname || 'Workbook.xls';
      link.target = '_blank';
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    }
  })();
  
  <table id="tbl1" class="table2excel">
                    <tr>
                        <td>Product</td>
                        <td>Price</td>
                        <td>Available</td>
                        <td>Count</td>
                    </tr>
                    <tr>
                        <td>Bred</td>
                        <td>1
</td>
                        <td>2
</td>
                        <td>3
</td>
                    </tr>
                    <tr>
                        <td>Butter</td>
                        <td>4
</td>
                        <td>5
</td>
                        <td >6
</td>
                    </tr>
                </table>
<hr>
  
  <table id="tbl2" class="table2excel">
                    <tr>
                        <td>Product</td>
                        <td>Price</td>
                        <td>Available</td>
                        <td>Count</td>
                    </tr>
                    <tr>
                        <td>Bred</td>
                        <td>7
</td>
                        <td>8
</td>
                        <td>9
</td>
                    </tr>
                    <tr>
                        <td>Butter</td>
                        <td>14
</td>
                        <td>15
</td>
                        <td >16
</td>
                    </tr>
                </table>


<button  onclick="tablesToExcel(['tbl1','tbl2'], ['ProductDay1','ProductDay2'], 'TestBook.xls', 'Excel')">Export to Excel</button>

【讨论】:

    【解决方案2】:

    我建议您为此使用 DataTables - https://datatables.net/。他们有这样做的内置方法。

    但如果您希望自定义更多内容,那么没有比 PHPExcel 更好的库了 - https://github.com/PHPOffice/PHPExcel

    【讨论】:

      【解决方案3】:

      html表格到excel通过jquery libary转换成多表格

      通过这个您可以轻松地将您的 html 表格转换为 excel 文件到多个选项卡中以获取更多帮助,请查看以下内容

      html文件

      <script src="https://cdn.jsdelivr.net/alasql/0.3/alasql.min.js"></script>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.7.12/xlsx.core.min.js"></script>
      
      <button onclick="saveFile()">Save XLSX file</button>
      

      javascript 文件

      window.saveFile = function saveFile () {
      var data1 = [{a:1,b:10},{a:2,b:20}];
          var data2 = [{a:100,b:10},{a:200,b:20}];
          var opts = [{sheetid:'One',header:true},{sheetid:'Two',header:false}];
          var res = alasql('SELECT INTO XLSX("restest344b.xlsx",?) FROM ?',
                           [opts,[data1,data2]]);
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-10-26
        • 1970-01-01
        • 2014-08-29
        • 2023-03-21
        • 2014-10-01
        • 2018-04-18
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多