Spire.Doc for.NET 是一款专门对 Word 文档进行操作的 .NET 类库。在于帮助开发人员无需安装 Microsoft Word情况下,轻松快捷高效地创建、编辑、转换和打印 Microsoft Word 文档。拥有近10年专业开发经验Spire系列办公文档开发工具,专注于创建、编辑、转换和打印Word/PDF/Excel等格式文件处理,小巧便捷。
Spire.Doc for.NET 最新下载https://www.evget.com/product/3368/download
我们已经演示了如何使用 Spire.Doc 从代码中向 word 文档添加形状。Spire.Doc 还支持通过索引删除单个形状或清除 word 文档中的所有形状。本文将说明如何在 C# 和 VB.NET 中从 word 文档中删除形状。
第 1 步:初始化 Document 类的新实例并从文件加载文档。
Document doc = new Document(); doc.LoadFromFile("Shapes.docx",FileFormat.Docx2010);
第 2 步:从文档中获取第一节和从该节中获取第一段。
Section section = doc.Sections[0]; Paragraph para = section.Paragraphs[0];
第 3 步:从第一段中获取形状。
ShapeObject shape = para.ChildObjects[0] as ShapeObject;
第 4 步:删除形状或所有形状。
//remove the third shape. para.ChildObjects.RemoveAt(2); clear all the shapes. //para.ChildObjects.Clear();
第 5 步:将文档保存到文件中。
doc.SaveToFile("Removeshape.docx",FileFormat.Docx2010);
从word文档中删除一个形状后的有效截图:
完整代码:
[C#]
using Spire.Doc; using Spire.Doc.Documents; using Spire.Doc.Fields; namespace RemoveShape { class Program { static void Main(string[] args) { Document doc = new Document(); doc.LoadFromFile("Shapes.docx", FileFormat.Docx2010); Section section = doc.Sections[0]; Paragraph para = section.Paragraphs[0]; ShapeObject shape = para.ChildObjects[0] as ShapeObject; //remove the third shape. para.ChildObjects.RemoveAt(2); clear all the shapes. //para.ChildObjects.Clear(); doc.SaveToFile("Removeshape.docx", FileFormat.Docx2010); } } }
[VB.NET]
Imports Spire.Doc Imports Spire.Doc.Documents Imports Spire.Doc.Fields Namespace RemoveShape Class Program Private Shared Sub Main(args As String()) Dim doc As New Document() doc.LoadFromFile("Shapes.docx", FileFormat.Docx2010) Dim section As Section = doc.Sections(0) Dim para As Paragraph = section.Paragraphs(0) Dim shape As ShapeObject = TryCast(para.ChildObjects(0), ShapeObject) 'remove the third shape. para.ChildObjects.RemoveAt(2) '''/clear all the shapes. 'para.ChildObjects.Clear(); doc.SaveToFile("Removeshape.docx", FileFormat.Docx2010) End Sub End Class End Namespace
以上便是如何在 C# 和 VB.NET 中从 word 文档中删除形状,如果您有其他问题也可以继续浏览本系列文章,获取相关教程,