我需要在Chrome浏览器的“ .XLSX”文件中导出数据,以下代码对于IE来说可以正常工作。
但是其他条件下的代码正在创建download.xls文件Chrome浏览器
sa = window.open('data:application/vnd.ms-excel,' + encodeURIComponent(tab_text));
下面是Button Click上使用的代码:
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,"ABCD.xlsx");
}
else //other browser not tested on IE 11
sa = window.open('data:application/vnd.ms-excel,' + encodeURIComponent(tab_text));
return (sa);
}
请对此提供帮助,谢谢。
请使用上述代码向我建议解决方案,我是javascript新手,无法在建议的链接中实施该解决方案。
我还使用了以下代码来创建.XLSX文件,代码正在创建文件,但文件为空并显示错误消息: “文件格式和扩展名不匹配。该文件可能已损坏或不安全……您是否仍要打开它?”
var a = document.createElement('a');
var data_type = 'data:application/vnd.ms-excel';
var table_div = tab_text; //Your tab_text
var table_html = table_div.replace(/ /g, '%20');
a.href = data_type + ', ' + table_html;
//setting the file name
a.download = 'exported_table.xlsx';
//triggering the function
a.click();
答案 0 :(得分:0)
您可以这样做:
window.saveAs(blob,filename);
function fnExcelReport(id, name) {
var tab_text = '<html xmlns:x="urn:schemas-microsoft-com:office:excel">';
tab_text = tab_text + '<head><xml><x:ExcelWorkbook><x:ExcelWorksheets>
<x:ExcelWorksheet>';
tab_text = tab_text + '<x:Name>Test Sheet</x:Name>';
tab_text = tab_text + '<x:WorksheetOptions><x:Panes></x:Panes></x:WorksheetOptions>
</x:ExcelWorksheet>';
tab_text = tab_text + '</x:ExcelWorksheets></x:ExcelWorkbook></xml></head><body>';
tab_text = tab_text + "<table border='1px'>";
var exportTable = $('#' + id).clone();
exportTable.find('input').each(function (index, elem) { $(elem).remove(); });
tab_text = tab_text + exportTable.html();
tab_text = tab_text + '</table></body></html>';
var fileName = name + '_' + parseInt(Math.random() * 10000000000) + '.xls';
//Save the file
var blob = new Blob([tab_text], { type: "application/vnd.ms-excel;charset=utf-8" })
window.saveAs(blob, fileName);
}`