I have two functions to export html tables into excel. First one "fnExcelReport" is to work for IE browsers and the second one "tableToExcel" is to work with all other browsers:
Export in case of IE (got from here):
<script type="text/javascript">
function fnExcelReport(tablename, worksheetname, filename){
var tab_text="<table border='2px'><tr bgcolor='#87AFC6'>";
var textRange; var j=0;
tab = document.getElementById('projectsTable'); // id of table
for(j = 0 ; j < tab.rows.length ; j++)
{
tab_text=tab_text+tab.rows[j].innerHTML+"</tr>";
//tab_text=tab_text+"</tr>";
}
tab_text=tab_text+"</table>";
//tab_text= tab_text.replace(/<A[^>]*>|<\/A>/g, "");//remove if u want links in your table
//tab_text= tab_text.replace(/<img[^>]*>/gi,""); // remove if u want images in your table
//tab_text= tab_text.replace(/<input[^>]*>|<\/input>/gi, ""); // reomves input params
var ua = window.navigator.userAgent;
var msie = ua.indexOf("MSIE ");
txtArea1.document.open("txt/html","replace");
txtArea1.document.write(tab_text);
txtArea1.document.close();
txtArea1.focus();
sa=txtArea1.document.execCommand("SaveAs",true,filename);
return (sa);
}
</script>
Export function in case of other than IE (got from here by @yuryi galanter):
<script type="text/javascript">
var tableToExcel = (function () {
var uri = 'data:application/vnd.ms-excel;base64,', 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]--></head><body><table>{table}</table></body></html>'
, base64 = function (s) {
return window.btoa(unescape(encodeURIComponent(s)))
}
, format = function (s, c) {
return s.replace(/{(\w+)}/g, function (m, p) {
return c[p];
})
}
return function (table, name, filename) {
if (!table.nodeType) table = document.getElementById(table)
var ctx = {worksheet: name || 'Worksheet', table: table.innerHTML}
document.getElementById("downloadListofProjects").href = uri + base64(format(template, ctx));
document.getElementById("downloadListofProjects").download = filename;
document.getElementById("downloadListofProjects").click();
//window.location.href = uri + base64(format(template, ctx))
}
})()
</script>
Both serves my purpose to export a html table, but my problem is the exported output in excel is not same in both case. In case of exporting done from internet explorer (IE), the areas outside of the exported table data is white and also the fonts are small and I also don't know how to set the worksheet name which I am getting when exporting done from all other browsers. So, I want two things:
- The formatting "tableToExcel" sets in "fnExcelReport" and
- The worksheet name applied in "fnExcelReport".
How can I achieve that? TIA