Excel : We found a problem with some content (NPOI C#)

161 Views Asked by At

I am creating a file Excel using NPOI and C#. Everything works fine when writing the workbook to filestream; I can open the file just created and read it with no problems.

Instead, I got "We found a problem with some content.. " when I try to read the Excel file after saving using MemoryStream:

using (var ms = new MemoryStream())
{
    wb.Write(ms);

    string saveAsFileName = string.Format("title-{0:d}.xlsx", DateTime.Now).Replace("/", "-");
    HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
    HttpContext.Current.Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}", saveAsFileName));
    HttpContext.Current.Response.Clear();
    HttpContext.Current.Response.BinaryWrite(ms.GetBuffer());
    HttpContext.Current.Response.End();
}

Eventually I still can read the Excel file but I'd like to get rid of this annoying message error.

Thank you.

2

There are 2 best solutions below

1
Sam On

This is likely not a problem with NPOI but rather a general Excel-File-Saving Problem.

Can you try this?

XSSFWorkbook wb;
string file = "file.xlsx";
// read Excel
using (FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read))
{
    wb = new XSSFWorkbook(fs);
}

// modify it
//..

// write Excel
using (var fs = new FileStream(file, FileMode.Create, FileAccess.ReadWrite))
{
    wb.Write(fs);
}
2
J i N On
using (var ms = new MemoryStream())
{
  wb.Write(ms);
  ms.Position = 0; //--Reset the position of MemoryStream

  string saveAsFileName = string.Format("title-{0:d}.xlsx", DateTime.Now).Replace("/", "-");
  HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
  HttpContext.Current.Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}", saveAsFileName));
  HttpContext.Current.Response.AddHeader("Content-Length", ms.Length.ToString());
  HttpContext.Current.Response.Clear();
  HttpContext.Current.Response.BinaryWrite(ms.ToArray()); // Use ToArray() instead of GetBuffer()
  HttpContext.Current.Response.End();
}