Keval
Keval

Reputation: 1859

Export html to Excel : when try to open file it gives prompt like file is corrupted

I am exporting html table to excel using javascript code on browser. All done but when i try to open the file in microsoft excel it gives prompt like :

"Excel cannot open the file 'filename.xlsx' because the file format for the file extension is not valid. Verify that the file has not been corrupted and that the file extension matches the format of the file.Do you want to open file now?"

If i press yes it works fine and all data gets displayed properly in excel.

i want to remove this prompt.

My JavaScript code is

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();
}

Upvotes: 4

Views: 6888

Answers (2)

Keval
Keval

Reputation: 1859

In the end it seems that it isn't possible to bypass this alert. If I convert HTML code to excel data that does open in excel, so I implemented server side code to generate pure excel and return that to the client instead of HTML data.

Upvotes: 2

ralh
ralh

Reputation: 2564

From what I understand, you are not actually building an .xls file. You are just creating a HTML file with a .xls extension. That's not the same. Excel seems to be able to read your HTML anyway, but it warns you, because the file format and extension don't match.

If you want to build true xls files take a look at various libraries that do that, for example: https://github.com/SheetJS/js-xlsx

Upvotes: 1

Related Questions