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?
After spending several hours the solutions is to use this excellent class http://blogs.msdn.com/jmstall/pages/sample-code-html-clipboard.aspx
This worked for me on Windows 7 and 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(); }
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:
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); }
Just build a temporary html file with your html content and insert it like below.
// 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);
来源:https://stackoverflow.com/questions/2363993/adding-html-text-to-word-using-interop