簡體   English   中英

使用C#從Word文檔中讀取粗體和斜體字

[英]Read words that are bold and Italic from word document using c#

我不知道如何將粗體和斜體字與普通字分開。

有人可以建議如何使用C#識別粗體和斜體字嗎?

這是我到目前為止的內容:

foreach (Word.Paragraph objparagraph in document.Paragraphs)
{
    string sLine = objparagraph.Range.Text;
    if (sLine.Contains(Font.Bold && Font.Italic))
    { 

    }
}

首先,我無法測試此代碼,因此我不保證它將起作用! 我提供了此信息,但想提前知道我的答案是AFAIK!

就是說,您當前正在執行的操作無法正常工作,因為您正在將Paragraph對象(包含所需的粗體和斜體信息)轉換為字符串對象( 包含粗體或斜體信息)。也就是說,您正在丟失在有機會測試是否存在粗體/斜體信息之前,您只想使用.Range屬性而不是使用.Range.Text屬性,代碼將如下所示:

foreach (Word.Paragraph objparagraph in document.Paragraphs)
{
    int TRUE_CODE = 1;     // I do NOT know if this is correct, it could be another number!

    Range rWords = objparagraph.Range.Text;
    foreach (Range word in rWords.Words
        if (word.Bold == TRUE_CODE)
        { 
             // handle bold case
        }
        if (word.Italic == TRUE_CODE)
             // handle italic case
        }
    }
}

由於我尚未測試此代碼,因此請注意,可能需要進行調整才能使其正確。 特別是,您會認為word.Bold和word.Italic會返回true或false,但不會。 相反,它們返回表示三個事物之一的整數。

true - the word is bold (or italic)
false - the word is _not_ bold (or italic)
wdUndefined - the word is something else (combination, etc.)

(有關此文檔,請參見下面的鏈接)問題是,我不知道每個類別都使用什么整數。 在上面的代碼片段中,我假設1映射為true,但這可能不正確! 希望這足以讓您入門。 編碼愉快!

http://msdn.microsoft.com/zh-CN/library/microsoft.office.interop.word.range.bold.aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-1

暫無
暫無

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

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