我是 C# 和 OpenXml 的新手。我需要幫助來閱讀 .docx 檔案并將每個段落存盤在陣列中。
我正在使用 OpenXml 讀取 word(.docx) 檔案。我能夠讀取檔案并列印它。但問題是我只能列印連接的段落。我找不到將每個段落存盤為字串陣列的方法(就像在 Python 中使用 docx 庫一樣,您會自動將段落存盤為字串串列,我正在尋找類似的東西)。
using System;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
OpenWordprocessingDocumentReadonly(@"E:\WordDocTest\Test.docx");
}
public static void OpenWordprocessingDocumentReadonly(string filepath)
{
// Open a WordprocessingDocument based on a filepath.
using (WordprocessingDocument wordDocument =
WordprocessingDocument.Open(filepath, false))
{
// Assign a reference to the existing document body.
Body body = wordDocument.MainDocumentPart.Document.Body;
Console.WriteLine(body.InnerText);
wordDocument.Close();
}
}
}
}
Test.docx 看起來像這樣
1. 測驗
這是測驗 1。測驗 1
部分 a。
2.沒有測驗
這是測驗2。
我得到的輸出是:TestThis is Test 1.Test1 part a.noTestThis is Test 2。
我想學習的是如何將每個段落或行存盤在字串陣列中并能夠遍歷該陣列。
uj5u.com熱心網友回復:
您可以避免使用陣列,而是釋放 Openxml 與 Linq 和 Lists 相結合的強大功能。如果你想處理段落,你可以創建一個這樣的串列:
var paras = body.OfType<Paragraph>();
然后,您可以使用 Where 對此進行擴展以回傳特定元素,例如:
var paras = body.OfType<Paragraph>()
.Where(p => p.ParagraphProperties != null &&
p.ParagraphProperties.ParagraphStyleId != null &&
p.ParagraphProperties.ParagraphStyleId.Val.Value.Contains("Heading1")).ToList();
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/411175.html
標籤:
