Skip to content

Download table as Excel file (JS)

  • Web

Found a great and easy way to export any HTML table through an Excel file on the click of a button!

This page on Codepedia shows how it is done. However, there is a warning that some available library’s are malicious and could create security leaks. The only right source seems to be this CDN:

The code to incorporate on your webpage consists of 4 parts:

Part 1: JS library in the header

<script type="text/javascript" src=""></script>

Part 2: Table to be exported

<table id="tbl_exporttable_to_xls" >

Part 3: Button to trigger the export

<button onclick="ExportToExcel('xlsx','<filename.xlsx>')">Download Excel sheet</button>

Part 4: JS export script

function ExportToExcel(type, fn, dl) {
 var elt = document.getElementById('tbl_exporttable_to_xls');
 var wb = XLSX.utils.table_to_book(elt, { sheet: "Sheet 1" });
 return dl ?
  XLSX.write(wb, { bookType: type, bookSST: true, type: 'base64' }) :
  XLSX.writeFile(wb, fn || ('MySheetName.' + (type || 'xlsx')));

Leave a Reply

Your email address will not be published. Required fields are marked *