如何在Word文档中编写HTML

本文关键字:HTML 文档 Word | 更新日期: 2023-09-27 18:10:01

如何使用c#在Word文档中编写HTML ?

我创建了一个类来帮助编写文档

using System;
using System.IO;
using Microsoft.Office.Interop.Word;
namespace WordExporter
{
    public class WordApplication : IDisposable
    {
        private Application application;
        private Document document;
        private string path;
        private bool editing;
        public WordApplication(string path)
        {
            this.path = path;
            this.editing = File.Exists(path);
            application = new Application();
            if (editing)
            {
                document = application.Documents.Open(path, ReadOnly: false, Visible: false);
            }
            else
            {
                document = application.Documents.Add(Visible: false);
            }
            document.Activate();
        }
        public void WriteHeader(string text)
        {
            foreach (Section wordSection in document.Sections)
            {
                var header = wordSection.Headers[WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
                header.Font.ColorIndex = WdColorIndex.wdDarkRed;
                header.Font.Size = 20;
                header.Text = text;
            }
        }
        public void WriteFooter(string text)
        {
            foreach (Section wordSection in document.Sections)
            {
                var footer = wordSection.Footers[WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
                footer.Font.ColorIndex = WdColorIndex.wdDarkRed;
                footer.Font.Size = 20;
                footer.Text = text;
            }
        }
        public void Save()
        {
            if (editing)
            {
                application.Documents.Save(true);
            }
            else
            {
                document.SaveAs(path);
            }
        }
        #region IDisposable Members
        public void Dispose()
        {
            ((_Document)document).Close(SaveChanges: true);
            ((_Application)application).Quit(SaveChanges: true);
        }
        #endregion
    }
    class Program
    {
        static void Main(string[] args)
        {
            using (var doc = new WordApplication(Directory.GetCurrentDirectory() + "''test.docx"))
            {
                doc.WriteHeader("<h1>Header text</h1>");
                doc.WriteFooter("<h1>Footer text</h1>");
                doc.Save();
            }
        }
    }
}

WriteHeader中,我在文档标题上写了一些文本,但我需要使用HTML。我怎么能说内容是HTML呢?我还需要在文档内容中插入HTML…

如何在Word文档中编写HTML

我可以在我想要的部分插入html文件:

range.InsertFile("file.html");