簡體   English   中英

如何在c#中從word文檔.doc或.docx中獲取兩個標題之間的所有文本

[英]How to get all text between two Headings from a word Document .doc or .docx in c#

如何獲取兩個標題之間的所有文本或特定標題下的文本? 喜歡..

“標題ABC”

“標題XYZ”
這是XYZ標題下的內容
測試..

“XYZ 的副標題或標題 2”
XYZ 航向繼續

“標題 123” 標題 123下的內容

我想獲取 XYZ 標題的所有內容,包括子標題,直到出現下一個標題 123。我如何找到該特定標題,然后在 c# 中獲取該標題下的所有內容? 文件可以是 .doc 或 .docx

您可以使用NPOI庫閱讀 Word 文檔。 一些示例代碼可以幫助您入門。

public string ReadAllTextFromWordDocFile(string fileName)
{
    using (StreamReader streamReader = new StreamReader(fileName))
    {
        var document = new HWPFDocument(streamReader.BaseStream);
        var wordExtractor = new WordExtractor(document);
        var docText = new StringBuilder();
        foreach (string text in wordExtractor.ParagraphText)
        {
            docText.AppendLine(text.Trim());
        }
        streamReader.Close();
        return docText.ToString();
    }
}

稍微玩一下。

您還想看看DocX 基本示例在這里 每個段落的MagicText屬性可能會幫助您識別標題。

 private void DocReader(string fileLocation,string headingText, string headingStyle)
    {
        Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();
        object miss = System.Reflection.Missing.Value;
        object path = fileLocation;
        object readOnly = true;
        Microsoft.Office.Interop.Word.Document docs = word.Documents.Open(ref path, ref miss, ref readOnly, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss);
        string totaltext = "";
        int ind = 0;
        bool flag = false;

        int paraCount = docs.Paragraphs.Count;
        for (int i = 1; i < paraCount; i++)
        {
            Microsoft.Office.Interop.Word.Style style = docs.Paragraphs[i].get_Style() as Microsoft.Office.Interop.Word.Style;
            if (style != null && style.NameLocal.Equals(headingStyle))
            {
                flag = false;
                if (docs.Paragraphs[i].Range.Text.ToString().TrimEnd('\r').ToUpper() == headingText.ToUpper())
                {
                    ind++;
                    flag = true;
                }
            }
            if (flag && ind>=1)
                totaltext += " \r\n " + docs.Paragraphs[i].Range.Text.ToString();

        }
        if (totaltext == "") { totaltext = "No such data found!"; }
        richTextBox1.Text = totaltext;
        docs.Close();
        word.Quit();  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM