1

我想在 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>");
4

1 回答 1

3

您可以使用 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();
        }
    }
}
于 2013-08-14T11:30:14.587 回答