Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error dialog displayed when opening an excel file generated with EPPlus

I am creating an Excel file using the EPPlus library. When I create file and open up the file, the following pop up message shows:

We found a problem with some content in 'ExcelDemo.xlsx'. Do you want us to try to recover as much as we can? If you trust the source of this workbook, Click Yes

I am using following code

using (ExcelPackage pck = new ExcelPackage())
{
    //Create the worksheet
    ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Demo");

    //Load the datatable into the sheet, starting from cell A1. Print the column names on row 1
    ws.Cells[1, 2].Value = "Excel Download";

    Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
    Response.AddHeader("content-disposition", "attachment;  filename=ExcelDemo.xlsx");
    Response.BinaryWrite(pck.GetAsByteArray());
}

Is there problem in my code or is this an Excel issue?

like image 273
Waqas Ali Avatar asked Sep 09 '14 17:09

Waqas Ali


People also ask

What is EPPlus DLL?

EPPlus is a very helpful open-source 3rd party DLL for writing data to excel. EPPlus supports multiple properties of spreadsheets like cell ranges, cell styling, charts, pictures, shapes, comments, tables, protection, encryption, pivot tables, data validation, conditional formatting, formula calculation, etc.

What is EPPlus library?

What is EPPlus? A library to manage Excel spreadsheets. EPPlus is a . NET library, which reads and writes Excel 2007/2010 or higher files, using Open Office XML format. It supports .

Is EPPlus open source?

EPPlus was founded as an open source project by swedish programmer Jan Källman in 2009.


2 Answers

At the start, you need to add in a:

Response.Clear();

Then at the end add a

Response.End();
like image 170
Ads Avatar answered Sep 19 '22 05:09

Ads


In my case the problem was in calling

package.Save();

and using

Response.BinaryWrite(package.GetAsByteArray());

at the same time.

When you call package.GetAsByteArray() it perfoms following operations internally:

this.Workbook.Save();
this._package.Close();
this._package.Save(this._stream);

So, calling package.Save two times leads to this error when opening in Excel.

like image 23
tseshevsky Avatar answered Sep 19 '22 05:09

tseshevsky