我正在尝试使用 Office 互操作向 Word 添加一些 HTML 格式的文本。我的代码如下所示:
Clipboard.SetText(notes, TextDataFormat.Html);
pgCriteria.Range.Paste();
但它抛出了一个命令失败异常。任何的想法?
我正在尝试使用 Office 互操作向 Word 添加一些 HTML 格式的文本。我的代码如下所示:
Clipboard.SetText(notes, TextDataFormat.Html);
pgCriteria.Range.Paste();
但它抛出了一个命令失败异常。任何的想法?
花了几个小时后,解决方案是使用这个优秀的类 http://blogs.msdn.com/jmstall/pages/sample-code-html-clipboard.aspx
这在 Windows 7 和 Word 2007 上对我有用:
public static void pasteHTML(this Range range, string html)
{
Clipboard.SetData(
"HTML Format",
string.Format("Version:0.9\nStartHTML:80\nEndHTML:{0,8}\nStart" + "Fragment:80\nEndFragment:{0,8}\n", 80 + html.Length) + html + "<");
range.Paste();
}
样品用途:range.pasteHTML("a<b>b</b>c");
不使用剪贴板可能更可靠的方法是将 HTML 片段保存在文件中并使用InsertFile
. 就像是:
public static void insertHTML(this Range range, string html) {
string path = System.IO.Path.GetTempFileName();
System.IO.File.WriteAllText(path, "<html>" + html); // must start with certain tag to be detected as html: <html> or <body> or <table> ...
range.InsertFile(path, ConfirmConversions: false);
System.IO.File.Delete(path); }
在 word 文档中添加 html 有点棘手。最好的方法是创建一个临时文件,然后将此文件插入到单词的选定范围内。诀窍是利用Range的InsertFile函数。这允许我们通过首先将它们作为文件保存到磁盘上的临时位置来插入任意 HTML 字符串。
唯一的技巧是< html/>必须是文档的根元素。
我在我的一个项目中使用了类似的东西。
private static string HtmlHeader => "<html lang='en' xmlns='http://www.w3.org/1999/xhtml'><head><meta charset='utf-8' /></ head >{0}</html>";
public static string GenerateTemporaryHtmlFile(Range range,string htmlContent)
{
string path = Path.GetTempFileName();
File.WriteAllText(path, string.Format(HtmlHeader , htmlContent));
range.InsertFile(FileName: tmpFilePath, ConfirmConversions: false);
return path;
}
重要的是添加
字符集='utf-8'
到 html 文件的头部,否则在插入文件后,您可能会在 Word 文档中看到意外字符。
只需使用您的 html 内容构建一个临时 html 文件,然后将其插入如下。
// 1- Sample HTML Text
var Html = @"<h1>Sample Title</h1><p>Lorem ipsum dolor <b>his sonet</b> simul</p>";
// 2- Write temporary html file
var HtmlTempPath = Path.Combine(Path.GetTempPath(), $"{Path.GetRandomFileName()}.html");
File.WriteAllText(HtmlTempPath, $"<html>{Html}</html>");
// 3- Insert html file to word
ContentControl ContentCtrl = Document.ContentControls.Add(WdContentControlType.wdContentControlRichText, Missing);
ContentCtrl.Range.InsertFile(HtmlTempPath, ref Missing, ref Missing, ref Missing, ref Missing);