使用 Interop 将 html 文本添加到 Word
我正在尝试使用 Office Interop 将一些 HTML 格式的文本添加到 Word 中。我的代码如下所示:
Clipboard.SetText(notes, TextDataFormat.Html);
pgCriteria.Range.Paste();
但它抛出命令失败异常。有什么想法吗?
I'm trying to add some HTML formatted text to Word using Office Interop. My code looks like this:
Clipboard.SetText(notes, TextDataFormat.Html);
pgCriteria.Range.Paste();
but it's throwing a Command Failed exception. Any idea?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
花了几个小时后,解决方案是使用这个优秀的类
http://blogs.msdn.com/jmstall/pages/示例代码-html-clipboard.aspx
After spending several hours the solutions is to use this excellent class
http://blogs.msdn.com/jmstall/pages/sample-code-html-clipboard.aspx
这在 Windows 7 和 Word 2007 上对我有用:
示例使用:
range.pasteHTML("abc");
不使用剪贴板可能更可靠的方法是将 HTML 片段保存在文件中并使用
InsertFile
。像这样的东西:This worked for me on Windows 7 and Word 2007:
Sample use:
range.pasteHTML("a<b>b</b>c");
Probably a bit more reliable way without using the clipboard is to save the HTML fragment in a file and use
InsertFile
. Something like:在word文档中添加html有点棘手。最好的方法是创建一个临时文件,然后将该文件插入到单词的选定范围。诀窍是利用 Range 的 InsertFile 函数。这允许我们插入任意 HTML 字符串,方法是首先将它们作为文件保存到磁盘上的临时位置。
我在我的一个项目中使用了类似的东西。
添加很重要
到 html 文件的头部,否则插入文件后,您可能会在 Word 文档中看到意外的字符。
It is kind of tricky to add the html in a word document. The best way is creating a temporary file and than insert this file to selected range of the word. The trick is to leverage the InsertFile function of the Range. This allows us to insert arbitrary HTML strings by first saving them as files to a temporary location on disk.
I use something like this at one of my project.
it is important to adding
to head of html file other wise you may see unexpected characters at your word document after you insert file.
只需使用您的 html 内容构建一个临时 html 文件并将其插入,如下所示。
Just build a temporary html file with your html content and insert it like below.