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 <b>There</b><b>. </b><b>How </b>are <i>you </i><i>?</i>
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.
精彩评论