Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shaman.EPPlus + ASP.NET Core MVC - Part already exist exception

I am using Shaman.EPPlus, a version of EPPlus that should be compatible with ASP.NET Core MVC. I am trying to export a collection of object as xlxs file. The code looks like this:

foreach(var client in clientsToExport)
{
    clientList.Add(new object[] { "FirstName", client.FirstName });
}

MemoryStream stream = new MemoryStream();         
using (ExcelPackage pck = new ExcelPackage(stream))
{
    ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Clients");
    ws.Cells["A1"].LoadFromArrays(clientList);
    pck.Save();

    Response.Clear();
    Response.Headers.Add("content-disposition", "attachment;  filename=Clients.xlsx");
    Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
    var bytes = pck.GetAsByteArray();
    Response.Body.WriteAsync(bytes, 0, bytes.Length);
}

It seems that an exception containing the message "Par already exist" is thrown when GetAsByteArray method is called.

at OfficeOpenXml.Packaging.ZipPackage.CreatePart(Uri partUri, String contentType, CompressionLevel compressionLevel)
at OfficeOpenXml.ExcelWorkbook.Save()
at OfficeOpenXml.ExcelPackage.GetAsByteArray(Boolean save)

Do you know what could I check?

like image 283
Marius Istudor Avatar asked Oct 15 '16 22:10

Marius Istudor


1 Answers

The problem are these line:

pck.Save();
....
var bytes = pck.GetAsByteArray();

Both calls will cause the package to be closed by Epplus. You do not need the .Save call since that will automatically be called by .GetAsByteArray anyway so simply remove the first line.

like image 128
Ernie S Avatar answered Oct 06 '22 00:10

Ernie S