This question already has an answer here:
I couldn't find an existing question/answers on Stack Overflow for my particular issue so I'm posting this. I have an application written in HTML and jQuery/JavaScript. I need to export an HTML table into an Excel sheet using the jsxlsx (sheetsjs) plugin. I tried replicating their example to convert HTML table to Excel but the program errors out. Here's what I currently have:
My HTML code is inside a coldfusion page called books.cfm. I have my JavaScript in a file called Utils.js. These are:
function s2ab(s) {
var buf = new ArrayBuffer(s.length);
var view = new Uint8Array(buf);
for (var i=0; i<s.length; i++)
view[i] = s.charCodeAt(i) & 0xFF;
return buf;
}
function convertToExcel(event){
event.preventDefault();
console.log("button clicked");
var wb = XLSX.utils.table_to_book( $("#exceltable"), {sheet:"Exported
table"} );
saveAs(new Blob([s2ab(wb)],{type:"application/octet-stream"}),
'test.xlsx');
}
<html>
<head>
<script src="libs/jquery.min.js"></script>
<script src="libs/sheets/xlsx.full.min.js"></script>
<script src="libs/FileSaver/FileSaver.min.js"></script>
<script src="scripts/Utils.js"></script>
</head>
<body>
<table id="myTable">
<tr>
<td>ID</td>
<td>Name</td>
</tr>
<tr>
<td>1</td>
<td>Johnny</td>
</tr>
</table>
<button id="myBtn" onclick="convertToExcel(event)">Export</button>
</body>
</html>
When I run the above code and click on the button to convert to Excel, I get the following error:
**Uncaught TypeError: e.getElementsByTagName is not a function
at GC (xlsx.full.min.js:20)
at Object.jC [as table_to_book] (xlsx.full.min.js:20)
at exportErrsToExcel (Util.js:1227)
at HTMLButtonElement.onclick (books.cfm:18)**
Note: I got the above JavaScript code from this site.
New Answer With SheetJS Working code :
Old answer : You can use a workaround if sheetjs doesn't work. Datatable tool for instance has a plugin for exporting an HTML table to Excel. Demo : https://datatables.net/extensions/buttons/examples/initialisation/export.html
You could load Datatable in a hidden div for instance, and then your button "myBtn" launches the Export thanks to Excel Datatable export button