Search code examples
c#excelepplus

Adding data to the existing Excel sheet using Epplus LoadFromCollection() is corrupting the Excel Workbook


I have an Excel template stored which has around 25 sheets with some standard data already stored in those sheets. And I fetch the same template and fill the data to the existing sheets in it using LoadFromCollection method which corrupts the work book; I get an error

File Is corrupt cannot be opened

Get the file stored in S3 and pass the responseStream to Excel Package. Worksheet1 has the some data in cells till row 4 and column 4.

List listOfDummyData = someData;
MemoryStream outPutStream = new MemoryStream();

using (ExcelPackage excelPackage = new ExcelPackage(file.ResponseStream))
{
    ExcelWorksheets workSheets = excelPackage.Workbook.Worksheets;

    var worksheet = workSheets["worksheet1"];
    worksheet.Cells[4, 4, 4, 9].Clear();
    worksheet.Cells[4, 4, 4, 9].LoadFromCollection(listOfDummyData);    
    workSheets.saveAs(outPutStream);
}

Again this outPutStream is stored to aws S3. And when downloading the file again, it will be corrupted.


Solution

  • Here the worksheet.Cells[4, 4, 4, 9].Clear(); line was the culprit , Clear method was removing the all the existing formats of cells which use to cause the file corruption.