【问题标题】:"The file is corrupt and cannot be opened" error occurs on FileResultFileResult 上出现“文件已损坏且无法打开”错误
【发布时间】:2019-07-23 20:13:10
【问题描述】:

我有一个将数据表转换为 excel 字节并将其作为文件发送的 web api。当我尝试打开 excel 文件时,我收到“我们发现 'Test.xlsx' 中的某些内容存在问题。您希望我们尽可能恢复吗?如果您信任此工作簿的来源,请单击是的。”。当我单击是时,我得到“文件已损坏,无法打开”。

我已经尝试过以下堆栈溢出问题中提到的解决方案:

ASP.NET MVC FileResult is corrupting files

Excel file (.xlsx) created by saving byte stream in C# cannot be opened

issue with returning HttpResponseMessage as excel file in WebAPI

'The file is corrupt and cannot be opened' OpenXML

[HttpPost]
public FileResult GetExcelFile(string parameters)
{
      byte[] contents = generateContents(parameters);

      // Method 1:
      //Response.Clear();
//      Response.ContentType = "application/octet-stream";
  //    Response.AddHeader("Content-Disposition", "attachment; filename=" + "Test.xlsx");
    //  Response.AddHeader("Content-Length", contents.Length.ToString());
     // Response.BinaryWrite(contents);
//      Response.Flush();
  //    Response.Close();
    //  Response.End();


     return File(contents, "application/octet-stream", "Test.xlsx");
}

$.ajax({
            url: webMethod,
            type: "POST",
            data: jQuery.param(parameters),
            success: function (result, status, xhr) {
                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, '');
                    }
                }

                var blob = new Blob([result]);
                var link = document.createElement('a');
                link.href = window.URL.createObjectURL(blob);
                link.download = filename;
                link.click();
            }
        });

提前感谢您的帮助!

更新:

从控制器返回的文件大小为 4 KB,而在 ajax 端,接收到的 blob 大小为 7 KB。

【问题讨论】:

  • 这可能不是客户端的问题,可能是您生成文档的方式。你能先验证一下吗?也许不是调用 generateContents 调用,您可以读取任何有效的 excel 文件并查看。
  • @KrishnaChaithanyaMuthyala:与有效的 excel 文件相同的错误。有什么建议吗?
  • 好的...所以问题似乎出在客户端然后...首先,为什么这是一个 POST,如果它只是获取数据?那么为什么你在返回时没有使用正确的 mime-type,正如你给出的第一个链接中提到的那样?
  • 你的平台是什么?带有剃刀视图的 ASP.NET MVC 和 webAPI?您是否希望在单击按钮或其他内容时下载此文件?
  • 我将其更改为 HttpGet 并尝试使用 application/vnd.openxmlformats-officedocument.spreadsheetml.sheetapplication/vnd.ms-excelstackoverflow.com/questions/44559457/…stackoverflow.com/questions/51150454/…同样的回复

标签: c# excel npoi


【解决方案1】:

我不确定这是否有帮助。 目前,当我的文件在 javascript 端下载时,我正在执行一项类似的任务,并遇到其他类型的问题。但是创建和下载的部分就像一个魅力。 我没有使用 ajax,但这是我的代码:

在 javascript 中,我只是调用 Controller 和 HttpResponseMessage:

    XlsGlarm: function () {
        $('#mdlWait').modal('show');
        committente = globalCommittente;
        periodo = globalPeriodo;
        location.href = "Exports/XlsGLARM?CfCommit=" + committente + "&Periodo=" + periodo;
        $('#mdlWait').modal('hide');
    }

在 MVC 控制器中:

        public HttpResponseMessage XlsGLARM(string CfCommit, string Periodo)
    {
        // here I load an Excel Template and build the workbook
        // and fill it. But iit's not realted to your question.

            using (MemoryStream tmpStream = new MemoryStream())
            {
                Response.Clear();
                Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                Response.AddHeader("content-disposition", "attachment;filename=" + fileName);
                workbook.Write(tmpStream);
                Response.BinaryWrite(tmpStream.ToArray());
                Response.End();
                return null;
            }

        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

最后我从浏览器下载了我的文件,我用 Chorme、IE 和 Modzilla 对其进行了测试。

【讨论】:

  • R:我能够毫无问题地下载 excel 文件。但只有一行写入文件,其余行丢失。你遇到过这个问题吗?
【解决方案2】:

对我来说,我从源数据库获得的行数都可以正常工作。我也解决了拦截下载的等待过程。

 EsportaListaExcell: function (AnnoImposta) {
        Metronic.blockUI({ target: "#gestione", animate: true });

        var url = "Controllers/ExportController.aspx?Anno=" + AnnoImposta + "&Procedura=Flussi&Filtro=" + jQuery('#gwFlusso_filter input').val() +
                                                    "&CodiceEsito=" + jQuery('#gwFlusso_filter_stato select').val();
        window.location.href = url;

        $.ajax({
            url: url,
            //...                
            error: function () {
                Metronic.unblockUI('#gestione');
            },
            complete: function () {
                Metronic.unblockUI('#gestione');
                //hide loading?
            }
        });

    },

【讨论】:

    猜你喜欢
    • 2012-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-30
    • 2011-10-09
    • 2020-12-16
    • 2018-06-21
    • 1970-01-01
    相关资源
    最近更新 更多