简体   繁体   中英

Export html tables to multiple sheets xlsx file not xls using jQuery or JavaScript

I have requirement to export html tables on my web page to multiple sheets excel workbook with xlsx extension.

There are many threads in stackoverflow that tells way to export to xls file but i need to export to xlsx file

I need to do this using JQuery or javascript. Any help would be appreciated.

Note: Without knowing your approach because the implementation hasn't been started at your end as mentioned in the comments in your question, it is hard to understand your code structure. This example only exports one table, but you should be able to dig through the libraries documentation to find out the possible ways to merge different tables in single file. Just search for multiple sheet in single file with sheet js or check this SO answer . Implement your logic and if run into issues, update the question with the problem.

You can make use of the available javascript libraries to generate xlsx file. You will need to add following scripts on the page. The only drawback with this approach is 4 external libraries, so only load them on a page you need.

<script src="https://unpkg.com/xlsx/dist/shim.min.js"></script>
<script src="https://unpkg.com/xlsx/dist/xlsx.full.min.js"></script>
<script src="https://unpkg.com/blob.js@1.0.1/Blob.js"></script>
<script src="https://unpkg.com/file-saver@1.3.3/FileSaver.js"></script>

Create a table with your data

  <table id="tableToExport">
    <tr>
      <th>Name</th>
      <th>Email</th>
      <th>Country</th>
    </tr>
    <tr>
      <td>John Doe</td>
      <td>john@mailserver.com</td>
      <td>USA</td>
    </tr>
    <tr>
      <td>Jane Doe</td>
      <td>jane@mailserver.com</td>
      <td>UK</td>
    </tr>
  </table>

Add event listener on a button or any element to trigger export.

var btn = document.getElementById("createXLSX");
var fileName = "test";
var fileType = "xlsx";
btn.addEventListener("click", function() {
   var table = document.getElementById("tableToExport");
   var wb = XLSX.utils.table_to_book(table, {sheet: "Sheet JS"});
   return XLSX.writeFile(wb, null || fileName + "." + (fileType || "xlsx"));
});

Check out this codepen to see the functionality.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM