I'm in the process of upgrading a project from VS 2012 to 2015, I'm down to the final error, which is getting Excel files to export. I'm using NPOI to create the Excel file and the code below to export it. Once the code hits the Response.End() line, I get the following error message:
Exception Thrown: 'System.Threading.ThreadAbortException' in mscorlib.dll Additional information: Thread was being aborted.
The file still downloads however and opens up perfectly. I tried commenting out the Response.End() line, and received no error from the code, however, when opening the Excel file I get this error:
We found a problem with some content in 'ContactNPOI.xlsx'. Do you want us to try to recover as much as we can? If you trust the source of this workbook, click Yes.
So I assuming without Response.End() the stream isn't closing properly or something? I started to research and discovered that this is a known issue, and to try using HttpContext.Current.ApplicationInstance.CompleteRequest() instead of Response.End(). I tried this and received no error from the code, but unfortunately still received the above error when trying to open the Excel file.
Below is my code snippet, can anyone suggest a fix to this, or perhaps a cleaner way to export Excel files?
XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet sh = (XSSFSheet)wb.CreateSheet("Instructional Hrs");
//Create Header Row
var headerRow1 = sh.CreateRow(0);
headerRow1.CreateCell(0).SetCellValue("Jimmy G Rocks!!");
using (var stream = new MemoryStream())
{
Response.Clear();
wb.Write(stream);
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}", "ContactNPOI.xlsx"));
Response.BinaryWrite(stream.ToArray());
Response.Flush();
Response.End();
//HttpContext.Current.ApplicationInstance.CompleteRequest();
}