編輯 Word 文檔
為了糾正錯(cuò)誤的拼寫或在 Word 文檔中添加一些新內(nèi)容,用戶需要編輯現(xiàn)有的 Word 文檔。本指南演示了在 C# 和 VB.NET 中編輯 Word 文檔的解決方案。
Spire.Doc for .NET 是一款非常棒的.NET Word 組件,提供了一個(gè)Paragraph 類,用戶可以通過設(shè)置其屬性來編輯段落中的內(nèi)容。在此示例中,更新了標(biāo)題并在第二段中添加了新文本(標(biāo)題為第一段)。編輯結(jié)果如下圖所示。
首先,聲明一個(gè) Paragraph 實(shí)例,并將其值設(shè)置為第一個(gè)段落(標(biāo)題)。設(shè)置其 Text 屬性以更新原始內(nèi)容。其次,聲明另一個(gè)Paragraph實(shí)例,其值設(shè)置為Paragraph 2。調(diào)用 Paragraph.AppendText 方法為該段落添加新內(nèi)容。傳遞給此方法的重載是字符串文本。為了區(qū)分新內(nèi)容和現(xiàn)有內(nèi)容,本例中對新內(nèi)容進(jìn)行了格式化。聲明一個(gè) TextRange 實(shí)例并將其值設(shè)置為新添加的內(nèi)容。設(shè)置此 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 是一個(gè)易于使用的 Word 文檔操作組件,允許開發(fā)人員在 C# 和 VB.NET for .NET 中快速生成、編寫、編輯和保存 Word(Word 97-2003、Word 2007、Word 2010), Silverlight 和 WPF。
歡迎下載|體驗(yàn)更多E-iceblue產(chǎn)品
如需獲取更多產(chǎn)品相關(guān)信息請咨詢