Export HTML Table as XLSX File

Contrary to some opinions floating around the Internet, it is in fact possible to export an HTML table as an .xlsx document (as well as .xls, .csv, and others), using only client side code, thanks to the useful Sheet JS library. The .xlsx file format is the one used by the most recent version of Excel, so having a native way to export data in this format directly in the client browser can eliminate the need for requests to be sent to and from servers, as is conventionally done, and has many other advantages.

A perfect use case is when you retrieve data from some endpoint and display it as an HTML table using DataTables, and then giving the user an option to filter, modify, and export this data to their local machine. Below is a very simple demo of data I took from that website, and below that you can specify the file name and export file type below.

Please use the two inputs below to test this out.

File name:

File type:

There are four JS dependencies needed:

The drawback of generating XLSX, XLS, and CSV files in this manner is the fact that the four dependencies total a whopping 943 KB. I recommend only loading that JS file on the pages that are required to use this exporting functionality.

The somewhat over-engineered script below can be used to add an event listener to generate the table:

function createXLSXTableDemo() {
  var btn = document.getElementById('createXLSX');
  var fileName = document.getElementById("fileName");
  var fileType = document.getElementById("fileType");

  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.value + '.' + (fileType.value || 'xlsx')));