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.

NamePositionOfficeAgeStart dateSalary
Airi SatouAccountantTokyo332008/11/28$162,700
Angelica RamosChief Executive Officer (CEO)London472009/10/09$1,200,000
Ashton CoxJunior Technical AuthorSan Francisco662009/01/12$86,000
Bradley GreerSoftware EngineerLondon412012/10/13$132,000
Brenden WagnerSoftware EngineerSan Francisco282011/06/07$206,850
Brielle WilliamsonIntegration SpecialistNew York612012/12/02$372,000
Bruno NashSoftware EngineerLondon382011/05/03$163,500
Caesar VancePre-Sales SupportNew York212011/12/12$106,450
Cara StevensSales AssistantNew York462011/12/06$145,600
Cedric KellySenior Javascript DeveloperEdinburgh222012/03/29$433,060

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')));