翻譯|使用教程|編輯:胡濤|2022-07-26 11:41:37.657|閱讀 224 次
概述:本文主要介紹了如何用 C# 中的表格替換 Word 中的文本,歡迎查閱!
# 界面/圖表報表/文檔/IDE等千款熱門軟控件火熱銷售中 >>
相關鏈接:
這個主題只是我們在 Spire.Doc 論壇上的一位用戶提出的另一個請求。為了讓更多人了解這個功能,我們將在文章中通過一個示例演示來展示整個過程。此外,我們想提醒您,我們為付費用戶和測試用戶提供免費的定制演示。
作為一個專業的 .NET Word 組件,Spire.Doc 使開發人員能夠將指定段落替換為新創建的表格或現有表格。在本例中,示例 word 文件主體中的第 3 段將替換為新建的表格。
測試文件:
第 1 步:新建一個word文檔并加載測試文件。
Document doc = new Document(); doc.LoadFromFile(@"..\..\test.docx");
第 2 步:通過找到關鍵文本字符串“classical antiquity science”返回 TextSection。
Section section = doc.Sections[0]; TextSelection selection = doc.FindString("classical antiquity science", true, true);
第 3 步:從TextSection返回TextRange,然后通過TextRange獲取OwnerParagraph。
TextRange range = selection.GetAsOneRange(); Paragraph paragraph = range.OwnerParagraph;
第 4 步:返回指定段落的從零開始的索引。
Body body = paragraph.OwnerTextBody; int index = body.ChildObjects.IndexOf(paragraph);
第 5 步:創建一個新表。
Table table = section.AddTable(true); table.ResetCells(3, 3);
第 6 步:刪除段落并將表格插入到集合中指定索引處。
body.ChildObjects.Remove(paragraph); body.ChildObjects.Insert(index, table);
第 7 步:保存并啟動文件。
doc.SaveToFile("result.doc", FileFormat.Doc); System.Diagnostics.Process.Start("result.doc");
結果:
完整的 C# 代碼:
using Spire.Doc; using Spire.Doc.Documents; using Spire.Doc.Fields; namespace ReplaceText { class Program { static void Main(string[] args) { Document doc = new Document(); doc.LoadFromFile(@"..\..\test.docx"); Section section = doc.Sections[0]; TextSelection selection = doc.FindString("classical antiquity science", true, true); TextRange range = selection.GetAsOneRange(); Paragraph paragraph = range.OwnerParagraph; Body body = paragraph.OwnerTextBody; int index = body.ChildObjects.IndexOf(paragraph); Table table = section.AddTable(true); table.ResetCells(3, 3); body.ChildObjects.Remove(paragraph); body.ChildObjects.Insert(index, table); doc.SaveToFile("result.doc", FileFormat.Doc); System.Diagnostics.Process.Start("result.doc"); } } }
歡迎下載|體驗更多E-iceblue產品
本站文章除注明轉載外,均為本站原創或翻譯。歡迎任何形式的轉載,但請務必注明出處、不得修改原文相關鏈接,如果存在內容上的異議請郵件反饋至chenjj@fc6vip.cn