Reputation: 967
I am exporting a HTML table to and Excel format file and then downloading it as an .xls
. This works fine in Firefox, Chrome etc. but not as expected in IE.
Below is the function I am using. The final if
statement finds out if the browser is IE or otherwise.
function exportTable(obj) {
var tab_text="<table border='2px'><tr>";
var textRange; var j=0;
tab = obj;
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 you want links in your table
tab_text= tab_text.replace(/<img[^>]*>/gi,""); // remove if you want images in your table
tab_text= tab_text.replace(/<input[^>]*>|<\/input>/gi, ""); // removes 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 = window.open();
txtArea1.document.open("txt/html","replace");
txtArea1.document.write(tab_text);
txtArea1.document.close();
txtArea1.focus();
sa=txtArea1.document.execCommand("SaveAs",false,"export.xls");
txtArea1.window.close()
} else { //other browser not tested on IE 11
sa = window.open('data:application/vnd.ms-excel,' + encodeURIComponent(tab_text));
return (sa);
}
}
If it's IE, it creates a new window, writes the HTML output to it and then asks the user where to save the file. When the dialog appears, the user is forced to save the file as .html
or .txt
.
This is where it gets weird. Although the save as box forces the user to download it as either .html
or .txt
the file itself is saved as an .xls
.
Is it possible to disable this prompt? Or is there another work around for this? I do not want the end user to be confused by this.
Upvotes: 1
Views: 2705
Reputation: 8589
Try using a hidden iframe instead of a new window. That solved alot of issues for me. To support IE9, I ended up with this snippet:
if (event.data.browser !== 'IE') {
$.util.open('data:application/vnd.ms-excel,' + event.data.content);
return true;
}
else {
// The iframe already has to be included in the HTML, or you'll get a 'no access error'.
frame.document.open("txt/html","replace");
frame.document.write(event.data.content);
frame.document.close();
frame.focus();
command = frame.document.execCommand("SaveAs", true, "data_table.xls");
return command;
}
The only downside is that its not a 'real' excel .xls file yet until you open it the first time and resave it as a .xls This technique is just leveraging excels ability to understand basic html markup.
A better, but way more complicated method is to actually construct a base64 encoded 'string' as shown in msdn documentation, but in the end this sufficed for the project.
Or as with all things, there's lotsa libraries that will do this for you.
Upvotes: 1