开发者

Capture word text as html

开发者 https://www.devze.com 2023-03-30 22:26 出处:网络
I am working on MS Word application capturing tool in which we capture selected contentsvia some keystrokes. All things done.

I am working on MS Word application capturing tool in which we capture selected contents via some keystrokes. All things done. Now in selected range i would like to capture text as html for example

Text = Hello There. How are you ?

I have done above query by below code sample

string str = string.Empty;
Word.Range rngFindBold =
    ((Word.DocumentClass)(wh.Document)).ActiveWindow.Selection.Range;
rngFindBold.Find.Font.Bold = -1;
foreach (Word.Range rngWord in rngFindBold.Words)
{
    if (rngWord.Bold != 0)
    {
        // rngWord.Bold = 0;
        //rngWord.Text = "<b>" + rngWord.Text + "</b>";
        str += "<b>" + rngWord.Text + "</b>";
    }
    else if (rngWord.Italic != 0)
    {
        // rngWord.Italic = 0;
        //  rngWord.Text = "<i>" + rngWord.Text + "</i>";
        str += "<i>" + rngWord.Text + "</i>";
    }
    else if (rngWord.Underline != 0)
    {
        //  rngWord.Underline = 0;
        //  rngWord.Text = "<u>" + rngWord.Text + "</u>";
        str += "<u>" + rngWord.Text + "</u>";
    }
    else
    {
        str += rngWord.Text开发者_开发百科;
    }
}

Result = Hello &lt;b&gt;There&lt;/b&gt;&lt;b&gt;. &lt;/b&gt;&lt;b&gt;How &lt;/b&gt;are &lt;i&gt;you &lt;/i&gt;&lt;i&gt;?&lt;/i&gt;

Above code takes more time when selecting multiline content

How can i optimize above code?


Instead of using += use a StringBuilder object. This handles string operations much more efficient.

That would change your code into :

StringBuilder builder = new StringBuilder();
Word.Range rngFindBold =
((Word.DocumentClass)(wh.Document)).ActiveWindow.Selection.Range;
rngFindBold.Find.Font.Bold = -1;
foreach (Word.Range rngWord in rngFindBold.Words)
{
    if (rngWord.Bold != 0)
    {
        builder.Append("<b>" + rngWord.Text + "</b>");
    }
    else if (rngWord.Italic != 0)
    {
        builder.Append("<i>" + rngWord.Text + "</i>");
    }
    else if (rngWord.Underline != 0)
    {
        builder.Append("<u>" + rngWord.Text + "</u>");
    }
    else
    {
        builder.Append(rngWord.Text);
    }
}


Just one regular tip: use StringBuilder instead of concatination via add (+) operation.

Anyway performance of COM Interop is slow so bear with it.

0

精彩评论

暂无评论...
验证码 换一张
取 消