Export html to Excel: when trying to open the file, it gives hint how the file is damaged
I am exporting an html table to excel using javascript code in the browser. Everything is done, but when I try to open the file in microsoft excel it gives a hint like:
"Excel cannot open the file" filename.xlsx "because the file format for the file extension is not valid. Make sure the file is not damaged and the file extension matches the file format. Do you want to open the file?"
If I click yes it works fine and all data is displayed correctly in excel.
I want to delete this invitation.
My JavaScript code
function fnExcelReport()
{
var tab_text="<table border='2px'><tr bgcolor='#87AFC6'>";
var textRange; var j=0;
tab = document.getElementById('headerTable'); // 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 ");
if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)) // If Internet Explorer
{
txtArea1.document.open("txt/html","replace");
txtArea1.document.write(tab_text);
txtArea1.document.close();
txtArea1.focus();
sa=txtArea1.document.execCommand("SaveAs",true,"data.xls");
}
else{}
var a = document.createElement('a');
a.href = 'data:application/vnd.ms-excel,' + encodeURIComponent(tab_text);
a.download = 'rxe_data' + '.xls';
a.click();
}
source to share
From what I understand, you are not actually creating the .xls file. You just create an HTML file with a .xls extension. It is not the same. Excel seems to be able to read your HTML, but it warns you because the file format and extension are not the same.
If you want to build real xls files, take a look at the various libraries that do this, for example: https://github.com/SheetJS/js-xlsx
source to share