【发布时间】:2015-07-30 07:56:59
【问题描述】:
我正在使用浏览器上的 javascript 代码将 html 表导出到 excel。 一切都完成了,但是当我尝试在 microsoft excel 中打开文件时,它会给出如下提示:
"Excel 无法打开文件 'filename.xlsx',因为文件扩展名的文件格式无效。请确认文件没有损坏,并且文件扩展名与文件格式匹配。是否要现在打开文件吗?”
如果我按是,它工作正常,所有数据都会在 excel 中正确显示。
我想删除这个提示。
我的 JavaScript 代码是
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();
}
【问题讨论】:
-
您会收到提示,因为您正在打开一个扩展名为 .xls 的 HTML 文件,而不是本机 .xls 文件。在您的情况下,Excel 可以理解内容,因此您可以看到该文件。如果您尝试重命名扩展名为 .xls 的 .pdf 文件,您将收到相同的消息,但在打开文件时不会得到相同的结果。
-
thanx @wf4 这个信息,我明白了你的意思,但是有什么办法让我没有得到这个提示吗?
-
如果它用于网络下载,那么这将取决于您使用的服务器语言,例如PHP、C# 等Google Search
-
@wf4 我在服务器端使用 java,但如果我能在客户端做就太好了,因为所有事情都完成了,问题就是这个提示。
-
你可以试试SheetJS。可以参考我的回答here
标签: javascript excel export-to-excel