编辑 Word 文档
为了纠正错误的拼写或在 Word 文档中添加一些新内容,用户需要编辑现有的 Word 文档。本指南演示了在 C# 和 VB.NET 中编辑 Word 文档的解决方案。
Spire.Doc for .NET 是一款非常棒的.NET Word 组件,提供了一个Paragraph 类,用户可以通过设置其属性来编辑段落中的内容。在此示例中,更新了标题并在第二段中添加了新文本(标题为第一段)。编辑结果如下图所示。
首先,声明一个 Paragraph 实例,并将其值设置为第一个段落(标题)。设置其 Text 属性以更新原始内容。其次,声明另一个Paragraph实例,其值设置为Paragraph 2。调用 Paragraph.AppendText 方法为该段落添加新内容。传递给此方法的重载是字符串文本。为了区分新内容和现有内容,本例中对新内容进行了格式化。声明一个 TextRange 实例并将其值设置为新添加的内容。设置此 TextRange 的 CharacterFormat 属性,包括 FontName、FontSize 和 TextColor。下载并安装 Spire.Doc for .NET并按照下面的代码编辑 Word 文档。
[C#]
using System.Drawing; using Spire.Doc; using Spire.Doc.Documents; using Spire.Doc.Fields; namespace EidtWord { class Program { static void Main(string[] args) { //Load Document Document document = new Document(); document.LoadFromFile(@"E:\Work\Documents\WordDocuments\Spire.Doc for .NET.docx"); //Update Text of Title Section section = document.Sections[0]; Paragraph para1 = section.Paragraphs[0]; para1.Text = "Spire.Doc for .NET Introduction"; //Add New Text Paragraph para2 = section.Paragraphs[1]; TextRange tr=para2.AppendText("Spire.Doc for .NET is stand-alone" +"to enables developers to operate Word witout Microsoft Word installed."); tr.CharacterFormat.FontName = "Cataneo BT"; tr.CharacterFormat.FontSize=12; tr.CharacterFormat.TextColor = Color.YellowGreen; //Save and Launch document.SaveToFile("Edit Word.docx", FileFormat.Docx); System.Diagnostics.Process.Start("Edit Word.docx"); } } }
[VB.NET]
Imports System.Drawing Imports Spire.Doc Imports Spire.Doc.Documents Imports Spire.Doc.Fields Namespace EidtWord Friend Class Program Shared Sub Main(ByVal args() As String) 'Load Document Dim document As New Document() document.LoadFromFile("E:\Work\Documents\WordDocuments\Spire.Doc for .NET.docx") 'Update Text of Title Dim section As Section = document.Sections(0) Dim para1 As Paragraph = section.Paragraphs(0) para1.Text = "Spire.Doc for .NET Introduction" 'Add New Text Dim para2 As Paragraph = section.Paragraphs(1) Dim tr As TextRange = para2.AppendText("Spire.Doc for .NET is stand-alone" & "to enables developers to operate Word witout Microsoft Word installed.") tr.CharacterFormat.FontName = "Cataneo BT" tr.CharacterFormat.FontSize = 12 tr.CharacterFormat.TextColor = Color.YellowGreen 'Save and Launch document.SaveToFile("Edit Word.docx", FileFormat.Docx) System.Diagnostics.Process.Start("Edit Word.docx") End Sub End Class End Namespace
Spire.Doc 是一个易于使用的 Word 文档操作组件,允许开发人员在 C# 和 VB.NET for .NET 中快速生成、编写、编辑和保存 Word(Word 97-2003、Word 2007、Word 2010), Silverlight 和 WPF。
欢迎下载|体验更多E-iceblue产品
如需获取更多产品相关信息请咨询