Replace bold text in MS Word 2007 with <b>text</b> using C#.NET

ぐ巨炮叔叔 提交于 2019-12-05 07:06:27

问题


I want to search all bold text occurrences in MS Word 2007 document, and replace each bold "text" with "< text >"

Like following pseudo-code

foreach boldText in WordDocument
{
    string replacedText = "< " + boldText + " >";
    WordDocument.replace(boldText ,replacedText );
}

WordDocument.save();

回答1:


What you could do is something like this:

private void ReplaceBoldText(Microsoft.Office.Interop.Word.Document doc)
{
    foreach(Microsoft.Office.Interop.Word.Range rng in doc.StoryRanges)
    {
        foreach (Microsoft.Office.Interop.Word.Range rngWord in rng.Words)
        {
            if (rngWord.Bold != 0)
            {
                rngWord.Bold = 0;
                rngWord.Text = "<b>" + rngWord.Text + "</b>";
            }
        }
    }
}

This will change every TEXT to <b>TEXT</b>. If you want to check each character to see if it is bold you would need to iterate through rngWord.Characters. You may need some extra work to encapsulate consecutive bold characters, but the basis is as above.

If you are only worrying about whole words then the above will work fine.

Hope this helps.



来源:https://stackoverflow.com/questions/5879880/replace-bold-text-in-ms-word-2007-with-btext-b-using-c-net

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!