Skip to content

Commit 9c6252f

Browse files
Fix: ExcelWorksheets.Delete throws NotSupportedException on ExcelChartsheet (#2367)
The Delete method was attempting to access the PivotTables collection on all worksheet types. However, ExcelChartsheet throws NotSupportedException when accessing PivotTables. Added a type guard to skip PivotTable cleanup for chart sheets. Co-authored-by: Lieven De Foor <lieven.de.foor@tvh.com>
1 parent e3877f5 commit 9c6252f

2 files changed

Lines changed: 45 additions & 7 deletions

File tree

src/EPPlus/ExcelWorksheets.cs

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -470,15 +470,18 @@ public void Delete(int Index)
470470
worksheet.Drawings.ClearDrawings();
471471
}
472472

473-
//Remove all comments
474-
if (!(worksheet is ExcelChartsheet) && worksheet.Comments.Count > 0)
473+
if (!(worksheet is ExcelChartsheet))
475474
{
476-
worksheet.Comments.Clear();
477-
}
475+
//Remove all comments
476+
if (worksheet.Comments.Count > 0)
477+
{
478+
worksheet.Comments.Clear();
479+
}
478480

479-
while(worksheet.PivotTables.Count>0)
480-
{
481-
worksheet.PivotTables.Delete(worksheet.PivotTables[0]);
481+
while (worksheet.PivotTables.Count > 0)
482+
{
483+
worksheet.PivotTables.Delete(worksheet.PivotTables[0]);
484+
}
482485
}
483486
//Delete any parts still with relations to the Worksheet.
484487
DeleteRelationsAndParts(worksheet.Part);
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
/*******************************************************************************
2+
* Required Notice: Copyright (C) EPPlus Software AB.
3+
* https://epplussoftware.com
4+
*
5+
* This library is free software; you can redistribute it and/or
6+
* modify it under the terms of the GNU Lesser General Public
7+
* License as published by the Free Software Foundation; either
8+
* version 2.1 of the License, or (at your option) any later version.
9+
*******************************************************************************/
10+
using System;
11+
using Microsoft.VisualStudio.TestTools.UnitTesting;
12+
using OfficeOpenXml;
13+
using OfficeOpenXml.Drawing.Chart;
14+
15+
namespace EPPlusTest.Issues
16+
{
17+
[TestClass]
18+
public class ChartSheetDeleteTests
19+
{
20+
[TestMethod]
21+
public void DeleteChartSheetShouldNotThrowNotSupportedException()
22+
{
23+
using (var package = new ExcelPackage())
24+
{
25+
var ws = package.Workbook.Worksheets.Add("Data");
26+
var chartSheet = package.Workbook.Worksheets.AddChart("ChartSheet", eChartType.ColumnClustered);
27+
28+
// This call previously threw NotSupportedException because it tried to access chartSheet.PivotTables
29+
package.Workbook.Worksheets.Delete(chartSheet);
30+
31+
Assert.AreEqual(1, package.Workbook.Worksheets.Count);
32+
}
33+
}
34+
}
35+
}

0 commit comments

Comments
 (0)