Downloading a file with webforms and EPPlus

与世无争的帅哥 提交于 2021-01-29 13:35:54

问题


I am implementing a small export feature for a legacy webforms application.

My export code right now is only headers (just testing the that I can successfully create a file):

public MemoryStream Export()
{
    var result = new MemoryStream();
    using (var p = new ExcelPackage())
    {
        var ws = p.Workbook.Worksheets.Add("Contacts");
        var col = 1;
        ws.Cells[1, col++].Value = "ID";
        ws.Cells[1, col++].Value = "First Name";
        ws.Cells[1, col++].Value = "Last Name";
        ws.Cells[1, col++].Value = "Email";
        ws.Cells[1, col++].Value = "Phone";
        ws.Cells[1, col++].Value = "Address";
        p.SaveAs(result);
    }

    return result;
}

Here is the button handler:

var ms = Export();
ms.WriteTo(HttpContext.Current.Response.OutputStream);
HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
HttpContext.Current.Response.AddHeader("Content-Disposition", $"attachment;filename=Contacts_{DateTime.Now:yyyyMMddhhmmss}.xlsx");
HttpContext.Current.Response.StatusCode = 200;
// HttpContext.Current.Response.End();

So one issue is that all the examples I find have the HttpContext.Current.Response.End() call at the end of the method, but if I do this, it throws an exception. Commenting this line out seems to work fine but that leads me to my main problem: when the file is saved and then opened in excel, Excel complains there is a problem with the file. My impression is that EPPlus makes well formed files, so what am I missing?

Update #1 I tried directly saving the EPPlus package to disk. That seems to work without issue. So the problem lies somewhere between writing the package to the memorystream and returning the result.


回答1:


Here is the code that is working for me

var ms = Export();
Response.Clear();
HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
HttpContext.Current.Response.AddHeader("Content-Disposition", $"attachment;filename=Contacts_{DateTime.Now:yyyyMMddhhmmss}.xlsx");
Response.AddHeader("Content-Length", ms.Length.ToString());
Response.BinaryWrite(ms.ToArray());
Response.End();


来源:https://stackoverflow.com/questions/59760412/downloading-a-file-with-webforms-and-epplus

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!