Html导出到Excel - 浏览器直接保存excel,不能打开“查看”模式,使用IE9 [英] Html Export to Excel - Browser directly saves the excel, cannot open in "View" mode, using IE9

查看:225
本文介绍了Html导出到Excel - 浏览器直接保存excel,不能打开“查看”模式,使用IE9的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用IE9将html表导出到excel,我已经使用以下js代码来导出我的表,它的工作正常,但我遇到的问题是,

I use IE9 to export an html table to excel, i have used the following js code to export my table which works fine, but the problem i face is,

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

when the export icon is clicked, the browser directly shows a saveAs option, which forces the user to save the excel before opening it, it doesn't allow to open the excel in view.

我的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);
}

当点击导出图标时,显示此对话框:

When export icon is clicked, it shows this dialog box:

我需要的是:

任何人都可以帮助我从浏览器获取上述对话框。真的很感激你的时间和帮助。

Can anyone please help me in getting the above dialog box from browser. Really appreciate your time and help.

推荐答案

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

Since you are using Java as your back-end, you will need to create a Java Web Service in your back-end or come up with appropriate servlet; either way you will need to change the url parameter in jquery ajax call in code below.

我已经测试过下面是ASP.Net和IE 9中的jQuery代码,其中它弹出一个对话框打开或保存下载的文件。所以这应该符合你的要求。

I have tested the jQuery code below in ASP.Net and IE 9, in which it did popup a dialog to Open or Save the downloaded file. So this should meet your requirements.

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

You can use code like below, in which a html string and file name of exported file are being posted to back-end.


  1. 后端servlet或Web服务应该有一个方法,将使用这两个参数来创建一个唯一名称在后端的某个文件夹下,并返回创建的文件的完整绝对URL。

  2. 在下面的代码示例中,此方法是一个Web服务方法称为 DownloadFile

  3. 当这个对后端的调用返回时,您将具有可以容易地导出的文件的URL通过将窗口的href设置为此URL来下载。

  4. 另外,请注意,即使将 fileName 作为参数传递后端,您需要确保将其转换为唯一的文件名。这是必要的,不同的用户可能会最终超额写入对方的文件。

  5. 例如,如果 exportExcel.xls 被传递到后端,则可以将GUID字符串附加到文件名,以便文件名成为: excelExport_bb1bf56eec4e4bc8b874042d1b5bd7da.xls 。这将使文件名始终是唯一的。

  1. The back-end servlet or web service should have a method that will take these two parameters to create a file with a unique name under some folder in back-end and return the full absolute URL of the file created.
  2. In code sample below, this method is a web service method called DownloadFile.
  3. When this call to back-end returns, you will have the URL to exported file which can be easily downloaded by setting window's href to this URL.
  4. Also, keep in mind that even though the fileName is being passed as a parameter to back-end, you need to make sure that it's converted to a unique file name. This is needed else different users might end up over-writing each other's files.
  5. For example, if exportExcel.xls is passed to back-end then you could append a GUID string to file name so the file name becomes: excelExport_bb1bf56eec4e4bc8b874042d1b5bd7da.xls. This will make the file name always unique.

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

    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)
}

这篇关于Html导出到Excel - 浏览器直接保存excel,不能打开“查看”模式,使用IE9的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆