EPPlus
EPPlus copied to clipboard
NullReferenceException in CopyDxfStylesTables
EPPlus usage
Noncommercial use
Environment
WIndows
Epplus version
7.3.2
Spreadsheet application
No response
Description
Similar to #1597, another NullReferenceException happens when copying sheets from one ExcelPackage to another, using this code:
ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
using ExcelPackage publishedPackage = ExcelPackage new NewExcelPackage(new FileInfo(excelFileName));
// Copy the sheets added to the Complete report up until now.
foreach (ExcelWorksheet completeSheet in workbook.Worksheets)
{
Logger.Log(" Copying sheet: " + completeSheet.Name);
// This is significantly faster compared to creating and populating all preceding sheets twice.
publishedPackage.Workbook.Worksheets.Add(completeSheet.Name, completeSheet);
}
The exception has this call stack:
at OfficeOpenXml.Core.Worksheet.WorksheetCopyHelper.CopyDxfStylesTables(ExcelWorksheet copy, ExcelWorksheet added)
at OfficeOpenXml.Core.Worksheet.WorksheetCopyHelper.CopyDxfStyles(ExcelWorksheet copy, ExcelWorksheet added)
at OfficeOpenXml.Core.Worksheet.WorksheetCopyHelper.CloneCellsAndStyles(ExcelWorksheet Copy, ExcelWorksheet added)
at OfficeOpenXml.Core.Worksheet.WorksheetCopyHelper.Copy(ExcelWorksheets targetWorksheets, String name, ExcelWorksheet sourceWorksheet)
at OfficeOpenXml.ExcelWorksheets.Add(String Name, ExcelWorksheet Copy)
This happens on below last line, because excelTable2 is null:
for (int j = 0; j < excelTable.Columns.Count; j++)
{
ExcelTableColumn excelTableColumn = excelTable.Columns[j];
ExcelTableColumn excelTableColumn2 = excelTable2.Columns[j]; // <-- NullReferenceException !
The likely reason it becomes null, is because the assignment looks like this:
ExcelTable excelTable2 = added.Tables[excelTable.Name];
while the preceding line assign the source like this:
ExcelTable excelTable = copy.Tables[i];
So, perhaps merely changing the offending line into this might solve it? ``ExcelTable excelTable2 = added.Tables[i];`