将Word文本捕获为html
我正在开发 MS Word 应用程序捕获工具,在该工具中我们通过一些按键捕获选定的内容。所有事情都完成了。 现在,在选定的范围内,我想将文本捕获为 html,例如
Text = Hello There。 你怎么样?
我已经通过下面的代码示例
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>你</b>怎么样</i< i>?</i>
以上代码在选择多行内容时需要更多时间
我如何优化以上代码?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用
StringBuilder
对象代替+=
。这可以更有效地处理字符串操作。这会将您的代码更改为:
Instead of using
+=
use aStringBuilder
object. This handles string operations much more efficient.That would change your code into :
只有一个常规提示:使用 StringBuilder 而不是通过添加 (+) 操作进行连接。
无论如何,COM Interop 的性能很慢,所以请耐心等待。
Just one regular tip: use StringBuilder instead of concatination via add (+) operation.
Anyway performance of COM Interop is slow so bear with it.