从服务器响应中获取Excel文件(.xlsx)

lzfw57am  于 2023-11-20  发布在  其他
关注(0)|答案(4)|浏览(100)

我有一个问题,得到Excel文件和打开下载窗口后,在浏览器中得到一个响应(在成功的方法)与该文件。我有适当的Content-Type and Content-Disposition headers,我试图使用Blob在JS和我无法实现我想要的-简单的文件下载。
我完成了几个版本的我的aplogs,其中之一是下面.我开发的aplogs返回excel文件,我不能正常打开,因为它的损坏(尽管.xlsx扩展名).
也许问题是Blob构造函数中使用了不适当的数据类型?
我尝试使用“xhr.response”代替success方法参数中的“data”,但它也不起作用。我在Chrome的开发人员工具中检查了响应头,它们设置正确。
重要的是-在服务器端创建的所有Excel工作簿都是正确的,因为它在以前的版本中工作时,数据是在URL中发送的,而不是在邮件中。
下面是Java/Spring服务器端的控制器方法:

response.reset();
response.setContentType("application/vnd.ms-excel");
response.addHeader("Content-Disposition","attachment;filename=\"" + className + " " +  title + ".xlsx\"");
    try (ServletOutputStream output = response.getOutputStream()){
        workbook.write(output);
        output.flush();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

字符串
My Ajax下载文件并打开下载窗口:

$.ajax({
    url: myUrl,
    type: 'POST',
    data: myData,
    success: function(data, status, xhr) {
        var contentType = 'application/vnd.ms-excel';

        var filename = "";
        var disposition = xhr.getResponseHeader('Content-Disposition');
        if (disposition && disposition.indexOf('attachment') !== -1) {
            var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
            var matches = filenameRegex.exec(disposition);
            if (matches != null && matches[1]) filename = matches[1].replace(/['"]/g, '');
        }
        console.log("FILENAME: " + filename);

        try {
            var blob = new Blob([data], { type: contentType });

            var downloadUrl = URL.createObjectURL(blob);
            var a = document.createElement("a");
            a.href = downloadUrl;
            a.download = filename;
            document.body.appendChild(a);
            a.click();

        } catch (exc) {
            console.log("Save Blob method failed with the following exception.");
            console.log(exc);
        }

wz3gfoph

wz3gfoph1#

看起来JQuery在处理来自响应的二进制数据时遇到了一些问题。我简单地使用了XMLHttpRequest,并将所有数据添加到URL中。

var request = new XMLHttpRequest();
request.open('POST', url, true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
request.responseType = 'blob';

request.onload = function(e) {
    if (this.status === 200) {
        var blob = this.response;
        if(window.navigator.msSaveOrOpenBlob) {
            window.navigator.msSaveBlob(blob, fileName);
        }
        else{
            var downloadLink = window.document.createElement('a');
            var contentTypeHeader = request.getResponseHeader("Content-Type");
            downloadLink.href = window.URL.createObjectURL(new Blob([blob], { type: contentTypeHeader }));
            downloadLink.download = fileName;
            document.body.appendChild(downloadLink);
            downloadLink.click();
            document.body.removeChild(downloadLink);
           }
       }
   };
   request.send();

字符串

eblbsuwk

eblbsuwk2#

经过这么多的搜索,从Web API中获取一个带有Unicode内容的Excel文件。最后,这段代码对我来说很有用:

$.ajax({
                type: 'GET',
                cache: false,
                url: "https://localhost:44320/WeatherForecast",
              
                xhrFields: {
                    // make sure the response knows we're expecting a binary type in return.
                    // this is important, without it the excel file is marked corrupted.
                    responseType: 'arraybuffer'
                }
            })
                .done(function (data, status, xmlHeaderRequest) {
                    var downloadLink = document.createElement('a');
                    var blob = new Blob([data],
                        {
                            type: xmlHeaderRequest.getResponseHeader('Content-Type')
                        });
                    var url = window.URL || window.webkitURL;
                    var downloadUrl = url.createObjectURL(blob);
                    var fileName = '';

                  

                    if (typeof window.navigator.msSaveBlob !== 'undefined') {
                        window.navigator.msSaveBlob(blob, fileName);
                    } else {
                        if (fileName) {
                            if (typeof downloadLink.download === 'undefined') {
                                window.location = downloadUrl;
                            } else {
                                downloadLink.href = downloadUrl;
                                downloadLink.download = fileName;
                                document.body.appendChild(downloadLink);
                                downloadLink.click();
                            }
                        } else {
                            window.location = downloadUrl;
                        }

                        setTimeout(function () {
                            url.revokeObjectURL(downloadUrl);
                        },
                            100);
                    }
                });

字符串

slsn1g29

slsn1g293#

我们最近遇到了同样的问题。对我们来说,当我们将responseType: 'arraybuffer'添加到ajax参数时,它就开始工作了。最好使用lib https://github.com/eligrey/FileSaver.js/而不是手动点击链接,因为这个工具也会收回内存。

uinbv5nw

uinbv5nw4#

在我例子中,这个sinpcode工作正常

$('.btnExportToExcel').click(async (e) => {
    e.preventDefault();
    const info = JSON.parse(e.currentTarget.dataset.info);
    let action = 1;
   

    try {
        const data = {
        idCampagna: info.idCampagna,
        fileName: info.fileName,
       };
         this.ShowSpinner("Downloading");

        // this.HideSpinner();

        $.ajax({
            type: 'GET',
            cache: false,
            url: "ExportToExcel",
            data: data,
            xhrFields: {
                // make sure the response knows we're expecting a binary type in return.
                // this is important, without it the excel file is marked corrupted.
                responseType: 'arraybuffer'
            }
        })
            .done(function (data, status, xmlHeaderRequest) {
                var downloadLink = document.createElement('a');
                var blob = new Blob([data],
                    {
                        type: xmlHeaderRequest.getResponseHeader('Content-Type')
                    });
                var url = window.URL || window.webkitURL;
                var downloadUrl = url.createObjectURL(blob);
                var fileName = '' +'.xls';


                if (typeof window.navigator.msSaveBlob !== 'undefined') {
                    window.navigator.msSaveBlob(blob, fileName);
                } else {
                    if (fileName) {
                        if (typeof downloadLink.download === 'undefined') {
                            window.location = downloadUrl;
                        } else {
                            downloadLink.href = downloadUrl;
                            downloadLink.download = fileName;
                            document.body.appendChild(downloadLink);
                            downloadLink.click();
                        }
                    } else {
                        window.location = downloadUrl;
                    }

                    setTimeout(function () {
                        url.revokeObjectURL(downloadUrl);
                    },
                        100);
                }
            });
        this.HideSpinner();
    } catch (error) {
        console.log(error);
    }
});

字符串

相关问题