1

我遇到用户应该通过 AJAX 请求导出数据并以某种方式通过 AJAX 接收下载文件的情况。

我正在尝试使用 ClosedXML 和 Firefox

客户端:

  $.ajax({
                type: "POST",
                url: 'someurl',
                dataType: "text",
                data: pData,

                success: function (response, status, xhr) {

                    // check for a filename

                    var disposition = xhr.getResponseHeader('Content-Disposition');
                    var filename = disposition;
                    console.log(xhr);


                    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, '');
                    }

                   // var type = xhr.getResponseHeader('Content-Type');
                    var blob = new Blob([response], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" });

                    if (typeof window.navigator.msSaveBlob !== 'undefined') { window.navigator.msSaveBlob(blob, filename); }
                    else {
                        var URL = window.URL || window.webkitURL;
                        var downloadUrl = URL.createObjectURL(blob);

                        if (filename) {
                            var a = document.createElement("a");
                            if (typeof a.download === 'undefined') { window.location = downloadUrl; }
                            else {
                                a.href = downloadUrl;
                                a.download = filename;
                                document.body.appendChild(a);
                                a.click();
                            }
                        } else { window.location = downloadUrl; }

                        setTimeout(function () { URL.revokeObjectURL(downloadUrl); }, 100); // cleanup
                    }
               }
            });

服务器端:

XLWorkbook wb = new XLWorkbook();
ExcelWorksheet ws = pck.Workbook.Worksheets.Add( "Animal" );
dt = getselect();
if(dt.Rows.Count > 0)
{wb.Worksheets.Add(dt, "Animals" );}

Response.Clear();
Response.Buffer = true;
Response.Charset = "";
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader( "content-disposition", "attachment;filename=SqlExport.xls" );


using ( MemoryStream MyMemoryStream = new MemoryStream() )
            {
                wb.SaveAs( MyMemoryStream ); 
                MyMemoryStream.WriteTo( Response.OutputStream );
                Response.Flush();
                Response.End();
            }

结果,我收到了一个文件,但 Excel 报告该文件已损坏且无法打开。

我做错了什么?

4

0 回答 0