我有一个将HTML表转换为Excel文档的函数。但是,在打开文件时,我收到来自Excel的以下消息:
'something.xls'的文件格式和扩展名不匹配。等等...
以下是我用于导出的函数,它是来自this线程的@SamPopes答案的略微编辑版本。 obj
参数是我使用table
创建的document.createElement('table');
元素。
是否有任何方法可以在打开文件时阻止此消息?
function export(obj) {
var tab_text="<table border='2px'><tr>";
var textRange; var j=0;
tab = obj; //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 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.document.open("txt/html","replace");
txtArea1.document.write(tab_text);
txtArea1.document.close();
txtArea1.focus();
sa=txtArea1.document.execCommand("SaveAs",true,"export.xls");
} else { //other browser not tested on IE 11
sa = window.open('data:application/vnd.ms-excel,' + encodeURIComponent(tab_text));
return (sa);
}
}
答案 0 :(得分:2)
正如我在上面的评论中所说,这是创建CSV文件的代码。这可以避免您收到的错误消息,但将消除您格式化数据的任何机会(据我所知)。这是我的代码,它使用一个进程用于IE,第二个用于所有其他浏览器:
function exportTotalDataFile(){
var dataText = "";
var rowText = "";
'allData is generated through an AJAX call that creates a JSON'
'this loop creates the header row'
for (var index in allData[0]) {
rowText += index + ',';
}
'takes the trailing comma out, adds new row'
rowText = rowText.slice(0, -1);
dataText += rowText + '\r\n';
'Produces the data rows'
for (var i = 0; i < allData.length; i++) {
var rowText = "";
for (var index in allData[i]) {
rowText += '"' + allData[i][index] + '",';
}
rowText.slice(0, rowText.length - 1);
dataText += rowText + '\r\n';
}
var fileName = "Losses Report";
'Internet Explorer logic'
var isIE = false || !!document.documentMode;
if (isIE){
var IEwindow = window.open();
IEwindow.document.write('sep=,\r\n' + dataText);
IEwindow.document.close();
IEwindow.document.execCommand('SaveAs', true, fileName + ".csv");
IEwindow.close();
}
'All the other browsers'
else {
var uri = 'data:text/csv;charset=utf-8,' + escape(dataText);
var link = document.createElement("a");
link.href = uri;
link.style = "visibility:hidden";
link.download = fileName + ".csv";
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
}
很抱歉,这种方法仅限于格式化部门,但我希望这会有所帮助