2011-09-28 100 views
1

如何使用C#在Word文檔中編寫HTML?如何在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文檔的內容...

回答

0

我剛插入的部分html文件我想用:

range.InsertFile("file.html");