编程语言
首页 > 编程语言> > c# – Shaman.EPPlus ASP.NET核心MVC – 部分已存在异常

c# – Shaman.EPPlus ASP.NET核心MVC – 部分已存在异常

作者:互联网

我使用的是Shaman.EPPlus,一个应该与ASP.NET Core MVC兼容的EPPlus版本.
我试图将对象的集合导出为xlxs文件.
代码如下所示:

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);
}

当调用GetAsByteArray方法时,似乎抛出了包含消息“Par已存在”的异常.

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

你知道我能检查什么吗?

解决方法:

问题是这些问题:

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

两次调用都会导致Epplus关闭包.你不需要.Save调用,因为无论如何都会自动调用.GetAsByteArray,所以只需删除第一行.

标签:c,export-to-excel,asp-net-core-mvc,epplus
来源: https://codeday.me/bug/20190611/1218732.html