Download table as Excel file (JS)

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: https://cdn.sheetjs.com.

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

Part 1: JS library in the header

<head>
<script type="text/javascript" src="https://cdn.sheetjs.com/xlsx-0.20.0/package/dist/xlsx.full.min.js"></script>
</head>

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

<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')));
 }
</script>

Leave a Reply

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