翻譯|使用教程|編輯:胡濤|2022-07-25 11:31:54.440|閱讀 209 次
概述:以下指南重點介紹如何通過Spire.Doc for .NET從 C# 中 Word 文檔的文本框中提取文本。
# 界面/圖表報表/文檔/IDE等千款熱門軟控件火熱銷售中 >>
相關鏈接:
文本框的目的是允許用戶輸入程序要使用的文本信息。也可以從文本框中提取現有的文本信息。以下指南重點介紹如何通過Spire.Doc for .NET從 C# 中 Word 文檔的文本框中提取文本。
首先,查看word文檔中的文本框信息。
其次,下載Spire.Doc 并安裝在您的系統上。Spire.Doc 安裝干凈、專業,并包含在 MSI 安裝程序中。
然后通過以下路徑在下載的 Bin 文件夾中添加 Spire.Doc.dll 作為參考:“..\Spire.Doc\Bin\NET4.0\ Spire.Doc.dll”。
現在介紹如何從文本框中提取文本的步驟。
第 1 步:從文件中加載一個 word 文檔。
Document document = new Document(); document.LoadFromFile(@"..\..\Test.docx");
第 2 步:檢查文檔中是否存在文本框。
//Verify whether the document contains a textbox or not if (document.TextBoxes.Count > 0)
第 3 步:初始化 StreamWriter 類以保存接下來要提取的文本
using (StreamWriter sw = File.CreateText("result.txt"))
第 4 步:從文本框中提取文本。
//Traverse the document foreach (Section section in document.Sections) { foreach (Paragraph p in section.Paragraphs) { foreach (DocumentObject obj in p.ChildObjects) //Extract text from paragraph in TextBox if (objt.DocumentObjectType == DocumentObjectType.Paragraph) { sw.Write((objt as Paragraph).Text) } //Extract text from Table in TextBox if (objt.DocumentObjectType == DocumentObjectType.Table) { Table table = objt as Table; ExtractTextFromTables(table, sw); } //Extract text from Table static void ExtractTextFromTables(Table table, StreamWriter sw) { for (int i = 0; i < table.Rows.Count; i++) { TableRow row = table.Rows[i]; for (int j = 0; j < row.Cells.Count; j++) { TableCell cell = row.Cells[j]; foreach (Paragraph paragraph in cell.Paragraphs) { sw.Write(paragraph.Text); } } } }
調試后會出現如下結果:
完整代碼:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Spire.Doc; using Spire.Doc.Fields; using System.IO; using Spire.Doc.Documents; namespace ExtractTextFromTextBoxes { class Program { static void Main(string[] args) { Document document = new Document(); document.LoadFromFile(@"..\..\Test.docx"); //Verify whether the document contains a textbox or not if (document.TextBoxes.Count > 0) { using (StreamWriter sw = File.CreateText("result.txt")) { foreach (Section section in document.Sections) { foreach (Paragraph p in section.Paragraphs) { foreach (DocumentObject obj in p.ChildObjects) { if (obj.DocumentObjectType == DocumentObjectType.TextBox) { TextBox textbox = obj as TextBox; foreach (DocumentObject objt in textbox.ChildObjects) { if (objt.DocumentObjectType == DocumentObjectType.Paragraph) { sw.Write((objt as Paragraph).Text); } if (objt.DocumentObjectType == DocumentObjectType.Table) { Table table = objt as Table; ExtractTextFromTables(table, sw); } } } } } } } } } static void ExtractTextFromTables(Table table, StreamWriter sw) { for (int i = 0; i < table.Rows.Count; i++) { TableRow row = table.Rows[i]; for (int j = 0; j < row.Cells.Count; j++) { TableCell cell = row.Cells[j]; foreach (Paragraph paragraph in cell.Paragraphs) { sw.Write(paragraph.Text); } } } } } }
歡迎下載|體驗更多E-iceblue產品
本站文章除注明轉載外,均為本站原創或翻譯。歡迎任何形式的轉載,但請務必注明出處、不得修改原文相關鏈接,如果存在內容上的異議請郵件反饋至chenjj@fc6vip.cn