Search code examples
exceldatatablec#-3.0epplus

Writing large object into excel is taking hell out of time. Any way to fix this?


I have a predefined format of an excel file and am writing my object into that excel which is taking lot of time and the application is going into stale mode.

I am using EpPlus library.

Please find the code below and let me know if I can make things better.

    FileInfo fileInfo = new FileInfo(xslxpath);
    using (ExcelPackage excelPackage = new ExcelPackage(fileInfo))
    {
      int excelRow = 2;
      ExcelWorksheet worksheet1 = excelPackage.Workbook.Worksheets.First();
      foreach (var rows in objDetails)
      {
        worksheet1.Cells[excelRow, 1].Value = rows.ID.ToString();
        worksheet1.Cells[excelRow, 2].Value = rows.Name.ToString();
        worksheet1.Cells[excelRow, 3].Value = rows.Days.ToString();
        worksheet1.Cells[excelRow, 4].Value = rows.Amount.ToString();
        worksheet1.Cells[excelRow, 5].Value = rows.Reason.ToString();
        WriteToLogFile(LogFile, excelRow.ToString() + " " + rows.IPNumber.ToString());

        worksheet1.Cells.AutoFitColumns();
        excelRow++;
        WriteToLogFile(LogFile, excelRow.ToString() + " " + rows.IPNumber.ToString());
      }

      excelPackage.Save();
    }

Solution

  • worksheet1.Cells.AutoFitColumns();
    

    You should call this once after your loop, not for each and every line.