4

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?

3 Answers 3

3

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); }
Sign up to request clarification or add additional context in comments.

4 Comments

Yeah, (+ 1 to you) using clipboard looks strange here
@R2D2 not sure what you mean .. but the clipboard is usually the least reliable way, because of the tiny chance of another application using it at the same time. I usually apply the formats programmatically for smaller ranges, or use templates with AutoText Building Blocks.
I am suing the clip board as the html I am loading is coming from a DB, Yes its bad I know. I am saying that the code needs to be marked as a Single thread to access the Clipboard
For the insertHTML solution, in the context of Outlook interop, don't forget to set Attachment: false so the HTML file will not be added as attachment!
1

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.

The only trick is that < html/> must be the root element of the document.

I use something like this at one of my project.

   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;
    }

it is important to adding

charset='utf-8'

to head of html file other wise you may see unexpected characters at your word document after you insert file.

1 Comment

In the context of Outlook interop, don't forget to set Attachment: false so the HTML file will not be added as attachment!
0

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);

1 Comment

In the context of Outlook interop, don't forget to set Attachment: false so the HTML file will not be added as attachment!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.