2011-12-15 66 views
1

我使用this library將html文本轉換爲文字格式。OpenXML Word - 將標題樣式添加到標題

一切正常。

我現在需要設計一些樣式。我現在用來生成文檔的是,我有一個標題和子標題和標題文本的列表,我使用每個循環來獲取標題和副標題及其文本並輸出它們,但我希望這些標題和副標題分配標題1到類別和標題2到子類別。這裏是我到目前爲止:

foreach循環來獲得名作和子類別,其文本

foreach (var category in ct) 
      { 
       strDocumentText.Append(category.ParentCat.CategoryName); 
       strDocumentText.Append("<br />"); 
       if(category.DocumentText != null) 
       { 
        strDocumentText.Append(category.DocumentText); 
       } 

       if (category.Children != null) 
       { 
        foreach (var subCategoreis in category.Children) 
        { 
         strDocumentText.Append("<p />"); 
         strDocumentText.Append(subCategoreis.ParentCat.CategoryName); 
         strDocumentText.Append("<br />"); 
         if (category.DocumentText != null) 
         { 

          strDocumentText.Append(subCategoreis.DocumentText); 
         } 
        } 
       } 

      } 

創建Word文檔:

StringBuilder strDocumentText = new StringBuilder(); 

string html = strDocumentText.ToString(); 
using (MemoryStream generatedDocument = new MemoryStream()) 
       { 
        BuildDocument(generatedDocument, html); 
        using (WordprocessingDocument wordDoc = WordprocessingDocument.Create(generatedDocument, WordprocessingDocumentType.Document)) 
        { 
         MainDocumentPart mainPart = wordDoc.MainDocumentPart; 
         if (mainPart == null) 
         { 
          mainPart = wordDoc.AddMainDocumentPart(); 
          new DocumentFormat.OpenXml.Wordprocessing.Document(new Body()).Save(mainPart); 
         } 

         HtmlConverter converter = new HtmlConverter(mainPart); 
         Body body = mainPart.Document.Body; 

         var paragraphs = converter.Parse(html); 
         for (int i = 0; i < paragraphs.Count; i++) 
         { 
          body.Append(paragraphs[i]); 
         } 

         mainPart.Document.Save(); 
        } 

        fs.Close(); 
        File.WriteAllBytes(saveFileDialog1.FileName, generatedDocument.ToArray()); 
+0

好的,讓我以另一種方式解釋這個..我如何設置段文本默認樣式(標題1,標題2)的文檔? – James 2011-12-15 13:55:18

回答

0

首先,你需要的樣式定義添加到該文件。構建OpenXml文檔時,不包括默認樣式。定義樣式之後,可以在段落屬性元素(序列化爲「pPr」)或運行元素屬性中引用它們。看看:http://msdn.microsoft.com/en-us/library/cc850838.aspx

相關問題