我正在使用Office Interop和MS Word(Microsoft.Office.Interop.Word)修改模板,用模板部分替换模板中的书签。我有一个方法可以做到这一点:
public void ReplaceBookmarkText(Bookmark bookmark, string newValue)
{
if (newValue != null) {
bookmark.Range.Text = newValue;
}
}
这适用于纯文本。我想创建一个新方法,其中第二个参数可以是HTML代码,代码转换为格式化文本,替换Range
的文本。如果我能按照自己的方式行事,我会写下这样的话:
public void ReplaceBookmarkTextWithHtml(Bookmark bookmark, string html)
{
if (newValue != null) {
bookmark.Range.Html = html;
}
}
当然,Html
不是Range
类的成员。我也尝试了以下内容:
public void ReplaceBookmarkTextWithHtml(Bookmark bookmark, string html)
{
if (newValue != null) {
bookmark.Range.FormattedText = html;
}
}
但是,这不起作用,因为FormattedText
属性的类型为Range
。
关于我如何做到这一点的任何想法?
答案 0 :(得分:1)
我能够做到的唯一方法是将html文本保存到临时的.html文件中,然后将文件插入到doc中,即:
bookmark.Range.InsertFile("tmp.html");
答案 1 :(得分:0)
这是我最终提出的解决方案。它涉及执行复制和粘贴。
public void ReplaceBookmarkTextWithHtml(Bookmark bookmark, string html)
{
if (html != null) {
Clipboard.SetData(DataFormats.Html, ClipboardFormatter.Html(html));
bookmark.Range.PasteSpecial(DataType: WdPasteDataType.wdPasteHTML);
}
}