C#删除Excel图表

我想从Excel文件中删除图表。 Excel文件是一个带图表的自动生成的历史文件,问题是,每次我更新历史时,它都会生成一个新的图表,但是旧的图表必须被删除…这是我的代码:

Excel.Workbook ExcelWorkBook = ExcelApp.Workbooks.Open(path); ExcelApp.Visible = true; Excel.Worksheet Sheet = (Excel.Worksheet)ExcelWorkBook.Worksheets.get_Item(1); Excel.Range range = Sheet.UsedRange; int i = 2; while (Convert.ToString((range.Cells[i, 1] as Excel.Range).Value2) != null) { i++; } Excel.Range oRange; Excel._Chart oChart; Excel.Series oSeries; oChart = (Excel._Chart)ExcelWorkBook.Charts.Add(Missing.Value, Missing.Value, Missing.Value, Missing.Value); oRange = Sheet.get_Range("A2:H" + i).get_Resize(Missing.Value, 8); oChart.ChartWizard(oRange, Excel.XlChartType.xlLineStacked, Missing.Value, Excel.XlRowCol.xlColumns, Missing.Value, Missing.Value, Missing.Value,"Chart01"); oSeries = (Excel.Series)oChart.SeriesCollection(1); oSeries.XValues = Sheet.get_Range("A2", "A" + i); oChart.Location(Excel.XlChartLocation.xlLocationAsObject, Sheet.Name); 

现在我需要在代码之前删除现有的图表。

就像是

  Excel._Chart asdf = Sheet.ChartObjects("Chart01").Chart; if (asdf != null) { asdf.Delete(); } 

这没有find名称为“Übersicht”的图表,但是有一个标题为“Übersicht”的图表

编辑:现在的问题是,它不能从HRESULT:0x800A03EC删除图表: exception

在Excel中,确保图表实际上以名称存在。

您可以使用重命名图表

 Sheets("Sheet1").ChartObjects(1).Name = "Chart01" 

那么当您在电子表格视图中单击图表时,您可以看到它实际上已重命名

在这里输入图像说明

在C#方面,我会build议这样一个最小的例子

 bool deleted = false; try { ChartObject myChart = ws.ChartObjects("Chart01"); myChart.Delete(); deleted = true; } catch { MessageBox.Show("Chart with this name could not be found"); //throw new Exception("Chart with this name could not be found"); } finally { MessageBox.Show("the chart was " + (deleted ? "deleted" : "not deleted")); } 

尝试将图表名称重新命名为“Chart01”。 这个问题可能是由于Unicode支持。