Search code examples
c#excelasp.net-coreepplus

EPPLus - export to Excel returns failed-network error


In my ASP.NET Core 1.1 app, I am exporting data to Excel using EPPLus.Core. But at the time of File download I get the error: Failed- network error

Controller

public async Task<FileStreamResult> CPT_RC_Excel(int FiscalYear)
{
    var custlist = _Context.Customers.Where(c => c.Region=="NW").ToList();

  MemoryStream ms = new MemoryStream();
  using (ExcelPackage pck = new ExcelPackage(ms))
  {
    ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Clients");
    ws.Cells["A1"].LoadFromCollection(custlist);

    Response.Clear();
    Response.Headers.Add("content-disposition", "attachment;  filename=TestFile.xlsx");
    Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
    var bytes = pck.GetAsByteArray();
    await Response.Body.WriteAsync(bytes, 0, bytes.Length);
    return File(ms, "application/force-download", "TestFile.xlsx");
  }
}

UPDATE:

  1. Error occurs on both Google Chrome and IE 11. The entire app is on a local desktop. No network drive is involved here.
  2. Error does seem to be related to the code above since another action method (code shown here) in the same controller does down load the csv/text files successfully.

Solution

  • You could try something like this:

    public async Task<ActionResult> CPT_RC_Excel(int FiscalYear)
            {
    
                var fileContentAsByteArray = [generate your file as a byte array]
    
                return File(fileContentAsByteArray, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "TestFile.xlsx");
    
            }
    

    if this doesn't work then the issue is with the file generation.

    try removing the reference to the MemoryStream and use...

    ...
    using (var excelPackage = new ExcelPackage())
    {
    ...
    }