我正试图使用以下代码从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();
}
}
它运行良好,但一些分组形状(如流程图(并没有被删除。
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:tempdoc1.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
项复制到另一个集合中。