javascript - Html导出Excel - 浏览器直接保存Excel,无法以 "View"模式打开,使用IE9

标签 javascript jquery html excel

我使用 IE9 将 html 表格导出到 Excel,我使用以下 js 代码导出我的表格,效果很好,但我面临的问题是,

当点击导出图标时,浏览器直接显示一个saveAs选项,强制用户在打开Excel之前保存Excel,并且不允许在中打开Excel查看

我的js函数:

function ExcelReport() {
var tab_text = "<table border='2px'><tr border='1px'>";
var tabcol = [];
var j = 0;
var i=0;
var temp;

tab = document.getElementById('myTable'); // id of table
var col = tab.rows[1].cells.length;

tab_text = tab_text + tab.rows[0].innerHTML + "</tr><tr>"; // table title row[0]

for (j = 1; j < tab.rows.length; j++) {
    for(i=0;i<col;i++){
        if(j==1){  // table header row[1]
                tabcol = tabcol + "<td bgcolor='#C6D7EC'>" + tab.rows[j].cells[i].innerHTML + "</td>";
            }else{
                tabcol = tabcol + "<td>" + tab.rows[j].cells[i].innerHTML + "</td>"; 
            }

    }
    if(j==1){  
        temp =  tabcol + "</tr>";
    }else{
        temp =  temp + tabcol + "</tr>";
    }
    tabcol = [];
}

tab_text = tab_text + temp + "</table>";

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,"MyExcelReport.xls");

} else
    //other browser not tested on IE 11
    sa = window.open('data:application/vnd.ms-excel,'+ encodeURIComponent(tab_text));

return (sa);
}

单击导出图标时,会显示以下对话框: enter image description here

我需要的是:

enter image description here

任何人都可以帮助我从浏览器获取上述对话框。非常感谢您的时间和帮助。

最佳答案

由于您使用 Java 作为后端,因此您需要在后端创建 Java Web 服务或提供适当的 servlet;无论哪种方式,您都需要更改下面代码中 jquery ajax 调用中的 url 参数。

我已经在 ASP.Net 和 IE 9 中测试了下面的 jQuery 代码,其中它确实弹出一个对话框来打开或保存下载的文件。所以这应该满足您的要求。

您可以使用如下代码,其中导出文件的 html 字符串和文件名被发布到后端。

  1. 后端 servlet 或 Web 服务应该有一个方法,该方法将采用这两个参数在后端的某个文件夹下创建一个具有唯一名称的文件,并返回完整的绝对 URL创建的文件。
  2. 在下面的代码示例中,此方法是一个名为 DownloadFile 的 Web 服务方法。
  3. 当对后端的调用返回时,您将获得导出文件的 URL,可以通过将窗口的 href 设置为此 URL 来轻松下载该文件。
  4. 此外,请记住,即使 fileName 作为参数传递到后端,您也需要确保将其转换为唯一的文件名。这是必需的,否则不同的用户最终可能会覆盖彼此的文件。
  5. 例如,如果将 exportExcel.xls 传递到后端,则您可以将 GUID 字符串附加到文件名,使文件名变为:excelExport_bb1bf56eec4e4bc8b874042d1b5bd7da.xls。这将使文件名始终是唯一的。

通过发布到后端导出到 Excel 的 jQuery 代码

    function ExportToExcel() {

    //create the html to be exported to Excel in any custom manner you like
    //here it's simply being set to some html string  
    var exportString = "<html><head><style>
    table, td {border:thin solid black} table {border-collapse:collapse}
    </style></head><body><table><tr><td>Product</td><td>Customer</td></tr>
    <tr><td>Product1</td><td>Customer1</td></tr><tr><td>Product2</td><td>Customer2</td>
    </tr><tr><td>Product3</td><td>Customer3</td></tr><tr><td>Product4</td>
    <td>Customer4</td></tr></table></body></html>";

    //set the file name with or without extension
    var fileName = "excelExport.xls";
    var exportedFile = { filePath: "", deleteFileTimer: null };

    //make the ajax call to create the Excel file
    $.ajax({
        url: "http://localhost/disera/ExportWebService/DownloadFile",
        type: "POST",
        data: JSON.stringify({ htmlString: exportString, fileName: fileName }),
        contentType: "application/json",
        async: true,
        success: function (data) {
            window.location.href = data.d;
            var exportedFile = { filePath: data.d, deleteFileTimer: null };

            //the line of code below is not necessary and you can remove it
            //it's being used to delete the exported file after it's been served
            //NOTE: you can use some other strategy for deleting exported files or
            //choose to not delete them
            DeleteFile(exportedFile);
        },
        error: function (xhr, ajaxOptions, thrownError) {
            alert("Following error occurred when exporting data to '" +
                    exportedFile.filePath + "' : " + thrownError);
        }
    });

}

function DeleteFile(exportedFile) {
    exportedFile.deleteFileTimer = setInterval(function () {
        $.ajax({
            url: "http://localhost/disera/ExportWebService/DeleteFile",
            type: "POST",
            data: JSON.stringify({ filePath: exportedFile.filePath }),
            contentType: "application/json",
            async: true,
            success: function (data) {
                if (data.d === true) {
                    clearInterval(exportedFile.deleteFileTimer);
                    exportedFile.deleteFileTimer = null;
                    exportedFile.filePath = null;
                    exportedFile = null;
                }
            },
            error: function (xhr, ajaxOptions, thrownError) {
                // alert("Following error occurred when deleting the exported file '" +
                // exportedFile.filePath + "' : " + thrownError);
            }
        });
    }, 30000)
}

关于javascript - Html导出Excel - 浏览器直接保存Excel,无法以 "View"模式打开,使用IE9,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36720402/

相关文章:

javascript - 字符串必须匹配 7 位数字以及集合中可选的非连续字符

javascript - 多次使用一个组件时如何一次触发或检测所有组件 - Ember

javascript - Google Chrome 中的部分内容请求

javascript - 为什么在 jquery 中动态创建的复选框定义属性的顺序会影响其值?

javascript - 在javascript中使用常规exp验证数字不适用于一种情况

ruby-on-rails - 使用 jquery 在 Rails 中渲染部分内容

javascript - 具有相同ID的多个元素的JQuery点击事件

javascript - 变量不适用于alsoResize : for colSelect

javascript - 检查 Angular HTML 中的 bool 真值

html - 字体媒体查询不起作用