Adding html text to Word using Interop

I am trying to add HTML text to Word using Office Interop. My code is as follows:

Clipboard.SetText(notes, TextDataFormat.Html); pgCriteria.Range.Paste(); 

but it throws a Command Failed exception. Any idea?

+4
source share
3 answers

After several hours, solutions should use this excellent class http://blogs.msdn.com/jmstall/pages/sample-code-html-clipboard.aspx

+4
source

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

Example usage: range.pasteHTML("a<b>b</b>c");

Probably a more reliable way without using the clipboard is to save the HTML fragment in a file and use InsertFile . Sort of:

 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); } 
+3
source

Just create a temporary html file with your html content and paste it as shown 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); 
0
source

Source: https://habr.com/ru/post/1302876/


All Articles