I am using the OfficeOpenXML
library to export excel data in my .NET MVC
Application. However I noticed something funny going on. I am able to download the file but when opening it I am prompted with the following message. If I hit "Yes" all the data is shown without any issues.
I noticed this prompt only shows up after a certain amount of data is written to the excel file. And not a huge amount. If I write 1000 rows of data as shown below the prompt shows, but 10 rows it doesn't show.
Code below:
public static ExcelPackage GenerateExcelFile<T>(ExcelPackage pck)
{
ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Data");
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn { ColumnName = "A" });
dt.Columns.Add(new DataColumn { ColumnName = "B" });
dt.Columns.Add(new DataColumn { ColumnName = "C" });
dt.Columns.Add(new DataColumn { ColumnName = "D" });
dt.Columns.Add(new DataColumn { ColumnName = "E" });
for (int i = 0; i < 1000; i++)
{
DataRow row = dt.NewRow();
row["A"] = "Value";
row["B"] = "Value";
row["C"] = "Value";
row["D"] = "Value";
row["E"] = "Value";
dt.Rows.Add(row);
}
ws.Cells["A1"].LoadFromDataTable(dt, true);
return pck;
}
This is taken from the following controller:
public HttpResponseMessage ExportGridToExcelWithFilters ()
{
using (ExcelPackage pck = new ExcelPackage())
{
var excelData = ExcelExportVM.GenerateExcelFile(pck);
using (MemoryStream ms = new MemoryStream())
{
excelData.SaveAs(ms);
HttpResponseMessage responsePackage = new HttpResponseMessage();
responsePackage.Content = new ByteArrayContent(ms.GetBuffer());
responsePackage.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
return responsePackage;
}
}
}
Changing the above code to produce less data:
for (int i = 0; i < 10; i++) //FROM 1000
{
DataRow row = dt.NewRow();
row["A"] = "Value";
row["B"] = "Value";
row["C"] = "Value";
row["D"] = "Value";
row["E"] = "Value";
dt.Rows.Add(row);
}
It now works and I am able to open the file without entering recovery mode.
I've had the same issue, this was caused by memorystream and the bad code :)
When you handle the stream after the file save, I can assume you are trying to send it somewhere, for example HttpResponse, and if you do MemoryStream
to byte[]
conversion there, that should not be done with GetBuffer()
method, call ToArray()
instead.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.