用c#创建包含html内容的word文档

本文关键字:word 文档 html 创建 包含 | 更新日期: 2023-09-27 18:27:34

我想在c#中创建一个包含html内容的word文档。但下面的代码显示的内容只是文本,而不是html格式。。。

这是我的代码:

Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application();  
              app.Visible=true;
              object template = Missing.Value;
              object newTemplate = Missing.Value;
              object documentType = Missing.Value;
              object visible = true;  //Show the doc while we work.
              _Document doc = app.Documents.Add(ref template,
                       ref newTemplate,
                       ref documentType,
                       ref visible);   
            doc.Words.First.InsertBefore ("<html><body>HTML content here!</body></html>");

用c#创建包含html内容的word文档

您可以使用HTML文件作为源:

using System;
using System.IO;
using System.Reflection;
using Microsoft.Office.Interop.Word;
using System.Windows.Forms;
class Program
{
    [STAThread]
    public static void Main()
    {
        var file = new FileInfo("input.html");
        Microsoft.Office.Interop.Word.Application app 
            = new Microsoft.Office.Interop.Word.Application();
        try
        {
            app.Visible = true;
            object missing = Missing.Value;
            object visible = true;
            _Document doc = app.Documents.Add(ref missing,
                     ref missing,
                     ref missing,
                     ref visible);
            var bookMark = doc.Words.First.Bookmarks.Add("entry");
            bookMark.Range.InsertFile(file.FullName);
        }
        catch (Exception)
        {
            throw;
        }
        finally
        {
            app.Quit();
        }
    }
}