How to export HTML table to Excel
Daisho Komiyama edited this page Aug 20, 2019
·
6 revisions
Hi, I've never been assigned a task to generate Excel files from scratch but somehow I've just got one and did it.
Here's the general idea of how I did it.
function generateExcel (fn, array) {
const fileName = 'my-export.xls';
const iframe = document.getElementsByTagName('iframe');
const table = fn(array);
if (window.navigator.userAgent.indexOf("MSIE ") > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)) {
//for IE
iframe.open("txt/html", "replace").write(table);
iframe.close();
return iframe.execCommand("SaveAs", true, fileName);
}
else {
//for browsers
const downloadLink = document.createElement("a");
document.body.appendChild(downloadLink);
downloadLink.href = 'data:application/vnd.ms-excel,' + encodeURIComponent(table);
downloadLink.download = fileName;
downloadLink.click();
}
}
function createStringTable (src) {
let table = '<table width="100%">';
//create table using src
table += '</table>';
return table;
}
generateExcel(createStringTable, data);
Disclaimer: this block of code produces an excel file with outdated format:xls (current version is xlsx) so when you try to open the excel file you just created, you'll get warning but it has no problem for general use cases.