Instantly share code, notes, and snippets.

Embed
What would you like to do?
Easy way to transfer HTML tables to Excel files, but with limited possibilities of customization
function tableToExcel(p){
var dlink=document.createElement('a');
document.body.appendChild(dlink);
var uri='data:application/vnd.ms-excel;base64,';
var template='<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--><meta http-equiv="content-type" content="application/vnd.ms-excel; charset=UTF-8"></head><body><table>{table}</table></body></html>';
var base64=function(s){return window.btoa(unescape(encodeURIComponent(s)));};
var format=function(s,c){return s.replace(/{(\w+)}/g,function(m,p){return c[p];});};
if(!p.table.nodeType) p.table = document.getElementById(p.table);
var ctx = { worksheet: p.worksheet || 'Worksheet', table: p.table.innerHTML };
dlink.href = uri + base64(format(template, ctx));
dlink.download = p.filename;
dlink.click();
document.body.removeChild(dlink);
}
tableToExcel({
table:document.getElementsById("someId"),
worksheet:"htmlTable",
filename:"filename.xls"
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment