Search code examples
c#asp.net-mvcexcelasp.net-mvc-5

ASP.NET MVC FileResult is corrupting files


I've been trying to get my ASP.NET MVC website to export some data as an Excel file. For hours I thought that NPOI was just producing garbage so I switched over to EPPlus. I tested it in LINQPad and it created a proper working XLSX file, so I moved the code over to the MVC app. AGAIN, I get corrupted files. By chance I happened to look at the temp directory and saw that the file created by EPPlus is 3.87KB and works perfectly, but the FileResult is returning a file that's 6.42KB, which is corrupted. Why is this happening? I read somewhere that it was the server GZip compression causing it, so I turned it off, and it had no effect. Someone, please help me, I'm going out of my mind... Here's my code.

[HttpGet]
public FileResult Excel(
    CenturyLinkOrderExcelQueryModel query) {
    var file = Manager.GetExcelFile(query); // FileInfo

    return File(file.FullName, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", query.FileName);
}

Solution

  • As far as I'm concerned there's an issue with the FileResult and it's accompanying methods. I ended up "resolving" the issue by overriding the Response object:

    [HttpGet]
    public void Excel(
        CenturyLinkOrderExcelQueryModel query) {
        var file = Manager.GetExcelFile(query);
    
        Response.Clear();
        Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
        Response.AddHeader("Content-Disposition", "attachment; filename=" + query.FileName);
        Response.BinaryWrite(System.IO.File.ReadAllBytes(file.FullName));
        Response.Flush();
        Response.Close();
        Response.End();
    }