【问题标题】:Grouped shapes not removed in MS Word using C#使用 C# 在 MS Word 中未删除的分组形状
【发布时间】:2022-09-23 01:19:35
【问题描述】:

我正在尝试使用以下代码从 word 文档中删除形状:

foreach (Microsoft.Office.Interop.Word.Shape shp in word.ActiveDocument.Shapes)
{
    shp.Delete();
}

foreach (Microsoft.Office.Interop.Word.InlineShape ilshp in word.ActiveDocument.InlineShapes)
{
    if (ilshp.Type == Microsoft.Office.Interop.Word.WdInlineShapeType.wdInlineShapePicture)
    {
        ilshp.Delete();
    }
}

它工作正常,但不会删除一些分组形状,如流程图。

    标签: c#


    【解决方案1】:

    Shapes 被分组到其他 Shapes 中,作为 GroupItems 集合中的一个项目。

    using Word = Microsoft.Office.Interop.Word;
    
    void DeleteShape(Word.Shape shp)
    {
        try
        {
            if (shp != null)
            {
                if ((int)shp.Type == 6  /* MsoShapeType.msoGroup */)
                {
                    Debug.WriteLine($"Deleting shape group {shp.Name} with {shp.GroupItems.Count} items");
    
                    //  it is not necessary to delete the group member shapes
                }
    
                Debug.WriteLine($"Deleting shape {shp.Name}");
                shp.Delete();
            }
        }
        catch(Exception ex)
        {
            Debug.WriteLine(ex.Message);
        }
    }
    

    简单地遍历形状集合来删除所有形状是行不通的。

    var word = new Word.Application();
    var doc = word.Documents.Open(@"C:\temp\doc1.docx");
    
    //  avoid problems deleting in current collection
    var list = new List<Word.Shape>();
    foreach(Word.Shape shape in word.ActiveDocument.Shapes)
    {
        list.Add(shape);
    }
    
    foreach (Word.Shape shape in list)
    {
        DeleteShape(shape);
    }
    

    如果删除当前的Shape 项目,则集合会损坏。您可以反向遍历集合,也可以将Shape 项复制到另一个集合中。

    【讨论】:

      猜你喜欢
      • 2017-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多