Search code examples
javascriptjqueryexport-to-excel

Exporting html table with dropdowns, to excel using jquery


I have a html table with a few cells containing dropdowns which I am trying to export to Excel using table2excel jquery plugin. The plugin exports all the cells except for the ones containing the select tag. How do I get around this problem?

Sample html:

<!DOCTYPE html>
<html>
<head>
    <script type="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]--></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>
</head>
<body>

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

<table id="testTable" summary="Sample tabe to export to excel" rules="groups" frame="hsides" border="2">
    <thead valign="top">
    <tr>
        <th>Col1</th>
        <th>Col2</th>
    </tr>
    </thead>
    <tbody>
    <tr>
        <td>Value1</td>
        <td>
            <select>
                <option value="option1">Option 1</option>
                <option value="option2" selected="selected">Option 2</option>
            </select>
        </td>
    </tr>
    </tbody>
</table>

</body>
</html>

Solution

  • You can generate a table HTML dynamically, so you can format the cell as per your need

    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: generateTable(table) };
        window.location.href = uri + base64(format(template, ctx));
      };
    })();
    function generateTable(table) {
      let innerHTML = `
            <thead  valign="top">
              <tr>
                ${Array.from(table.querySelectorAll("thead th ")).map(function(
                  columnHeader
                ) {
                  return `<th>${columnHeader.innerText}</th>`;
                }).join('')}
               </tr>
            </thead>
            <tbody>
              ${Array.from(table.querySelectorAll("tbody tr ")).map(
                function(row) {
                  return `<tr>
                            ${Array.from(row.querySelectorAll("td")).map(
                              function(cell) {
                                let text = "";
                                Array.from(cell.childNodes).forEach(childNode => {
                                  switch (childNode.nodeType) {
                                    case 1: {
                                      if (
                                        childNode.nodeName === "SELECT" ||
                                        childNode.nodeName === "INPUT"
                                      ) {
                                        text = text + childNode.value;
                                      }
                                      break;
                                    }
                                    case 3: {
                                      text = text + childNode.textContent;
    
                                      break;
                                    }
                                  }
                                });
    
                                return `<td>${text}</td>`;
                              }
                            ).join("")}</tr>`;
                }
              ).join("")}
            </tbody>
          `;
      console.log(innerHTML);
      return innerHTML;
    }
    <!DOCTYPE html>
    <html>
    
    <head>
      <script type="javascript">
        </script>
    </head>
    
    <body>
    
      <input type="button" onclick="tableToExcel('testTable', 'W3C Example Table')" value="Export to Excel">
    
      <table id="testTable" summary="Sample tabe to export to excel" rules="groups" frame="hsides" border="2">
        <thead valign="top">
          <tr>
            <th>Col1</th>
            <th>Col2</th>
          </tr>
        </thead>
        <tbody>
          <tr>
            <td>Value1</td>
            <td>
              <select>
                <option value="option1">Option 1</option>
                <option value="option2" selected="selected">Option 2</option>
              </select>
            </td>
          </tr>
        </tbody>
      </table>
    
    </body>
    
    </html>