Adding html text to Word using Interop

我只是一个虾纸丫 提交于 2019-11-28 10:28:06

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);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!