删除基于位置的图表?

时间:2014-02-17 20:28:38

标签: c# excel

是否可以根据工作簿中图表的位置删除Excel图表?例如,我目前正在使用下面的代码按名称删除图表。但我遇到的陷阱有时候图表有不同的名称。唯一一致的是它们位于同一个位置。或者有人可以将我的代码调整到基于位置删除的位置:

foreach (Microsoft.Office.Interop.Excel.Shape shp in oXL.Sheets["Sheet 1"].Shapes)
if (shp.Type == MsoShapeType.msoChart)
{
    if (shp.Name == "Chart 233" || shp.Name == "Chart 111") { shp.Delete(); }
}

1 个答案:

答案 0 :(得分:1)

像这样的东西 - 如果左上角位于B4范围内,将删除图表:D8

    //...
    using Office = Microsoft.Office.Core;
    using Excel = Microsoft.Office.Interop.Excel;
    using ios = System.Runtime.InteropServices;
    //...

    private void btnDeleteChart_Click(object sender, EventArgs e)
    {
        Excel.Application xl = GetExcel();
        if (xl == null) return;

        Excel.Workbook wb = xl.ActiveWorkbook;
        Excel.Worksheet sht = wb.ActiveSheet;
        Excel.Range rSrch = sht.Range["B4:D8"];

        Excel.Range rShp;

        foreach (Excel.Shape shp in sht.Shapes)
        if (shp.Type ==  Office.MsoShapeType.msoChart)
        {
            rShp = shp.TopLeftCell;
            if(xl.Intersect(rShp,rSrch)!=null)shp.Delete();
        }
    }

    private Excel.Application GetExcel()
    {
        Excel.Application xl = 
          (Excel.Application)ios.Marshal.GetActiveObject("Excel.Application");
        if (xl == null) MessageBox.Show("No Excel !!");
        return xl; 
    }