javascript - 使用 JavaScript/JQuery 将 html 表格数据导出到 Excel 在 chrome 浏览器中无法正常工作

标签 javascript jquery html excel google-chrome

我在 velocity 模板中有一个 HTML 表格。我想使用 java 脚本或 jquery 将 html 表数据导出到 excel,与所有浏览器兼容。 我正在使用下面的脚本

<script type="text/javascript">
function ExportToExcel(mytblId){
       var htmltable= document.getElementById('my-table-id');
       var html = htmltable.outerHTML;
       window.open('data:application/vnd.ms-excel,' + encodeURIComponent(html));
    }
</script>

此脚本在 Mozilla Firefox 中运行良好,它会弹出一个 excel 对话框,要求打开或保存选项。但是当我在 Chrome 浏览器中测试相同的脚本时,它没有按预期工作,当点击按钮时,没有弹出 excel。数据下载到“文件类型:文件”的文件中,没有像 .xls 这样的扩展名 chrome 控制台没有错误。

Jsfiddle 示例:

http://jsfiddle.net/insin/cmewv/

这在 mozilla 中可以正常工作,但在 chrome 中却不行。

Chrome 浏览器测试用例:

第一张图片:我点击导出到 excel 按钮

First Image:I click on Export to excel button

和结果:

Result

最佳答案

Excel 导出脚本适用于 IE7+、Firefox 和 Chrome。

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,"Say Thanks to Sumit.xls");
    }  
    else                 //other browser not tested on IE 11
        sa = window.open('data:application/vnd.ms-excel,' + encodeURIComponent(tab_text));  

    return (sa);
}

只需创建一个空白的 iframe:

<iframe id="txtArea1" style="display:none"></iframe>

调用此函数:

<button id="btnExport" onclick="fnExcelReport();"> EXPORT </button>

关于javascript - 使用 JavaScript/JQuery 将 html 表格数据导出到 Excel 在 chrome 浏览器中无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22317951/

相关文章:

javascript - 显示具有已检查输入的数据属性对象的元素

javascript - 如何使用 JayData 自定义 OData 服务器?

javascript - 格式化表头和表体

javascript - 查找包含选择器 id + 文本的元素

javascript - 将提示存储为对象值

javascript - 为什么在 onsubmit 返回 undefined 之后提交表单?

html - 在未嵌套的行之间 Bootstrap 移动元素

html - bootstrap well底部的定位按钮

javascript - 在选择选项中显示用于搜索的输入文本

javascript - 更改事件处理程序仅触发一次,jQuery