0

It says the stream is closed. I am just trying to figure out how I send back a blank .xls file.

ObjectDisposedException: Cannot access a closed Stream. System.IO.__Error.StreamIsClosed()

 [Produces("application/json")]
[Route("api/Report")]
public class ReportController : Controller
{
    [HttpGet]
    public ActionResult Get()
    {
        IWorkbook workbook = new XSSFWorkbook();
        ISheet sheet1 = workbook.CreateSheet("Sheet1");

        using (var exportData = new MemoryStream())
        {
            workbook.Write(exportData);
            string saveAsFileName = string.Format("Export-{0:d}.xlsx", DateTime.Now).Replace("/", "-");
            byte[] bytes = exportData.ToArray();
            return File(exportData, "application/vnd.ms-excel", saveAsFileName);
        }
    }
}
Brian Rogers
  • 125,747
  • 31
  • 299
  • 300
punkouter
  • 5,170
  • 15
  • 71
  • 116

1 Answers1

0

You are creating a byte array from the MemoryStream but you are not sending it to the File method. So the File method is trying to access the stream, but it is already closed by that point.

Change this line:

return File(exportData, "application/vnd.ms-excel", saveAsFileName);

To this:

return File(bytes, "application/vnd.ms-excel", saveAsFileName);
Brian Rogers
  • 125,747
  • 31
  • 299
  • 300