2013-05-20 73 views
2

我想使用Office Open XML SDK將自定義標題添加到Word文檔。我想繼承默認的Heading1風格,但出於某種原因,下面的代碼從頭開始創建styles.xml文件,並且只包含我的新樣式。將自定義標題添加到Word文檔

我希望生成的styles.xml也包含默認樣式(Normal,Heading1,Heading2,Heading3,...)。我該怎麼辦?

這裏是我的代碼:

 using (var package = WordprocessingDocument.Create(tempPath, WordprocessingDocumentType.Document)) 
     { 
      // Add a new main document part. 
      var mainPart = package.AddMainDocumentPart(); 

      var stylePart = mainPart.AddNewPart<StyleDefinitionsPart>(); 

      // we have to set the properties 
      var runProperties = new RunProperties(); 
      runProperties.Append(new Color { Val = "000000" }); // Color 
      runProperties.Append(new RunFonts { Ascii = "Arial" }); // Font Family 
      runProperties.Append(new Bold()); // it is Bold 
      runProperties.Append(new FontSize { Val = "28" }); //font size (in 1/72 of an inch) 

      //creation of a style 
      var style = new Style 
      { 
       StyleId = "MyHeading1", 
       Type = StyleValues.Paragraph, 
       CustomStyle = true 
      }; 
      style.Append(new StyleName { Val = "My Heading 1" }); //this is the name 
      // our style based on Heading1 style 
      style.Append(new BasedOn { Val = "Heading1" }); 
      // the next paragraph is Normal type 
      style.Append(new NextParagraphStyle { Val = "Normal" }); 
      style.Append(runProperties);//we are adding properties previously defined 

      // we have to add style that we have created to the StylePart 
      stylePart.Styles = new Styles(); 
      stylePart.Styles.Append(style); 
      stylePart.Styles.Save(); // we save the style part 

      ... 
     } 

這裏是產生styles.xml文件:

<?xml version="1.0" encoding="utf-8"?> 
    <w:styles xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"> 
    <w:style w:type="paragraph" w:styleId="MyHeading1" w:customStyle="true"> 
    <w:name w:val="My Heading 1" /> 
    <w:basedOn w:val="Heading1" /> 
    <w:next w:val="Normal" /> 
    <w:rPr> 
     <w:color w:val="000000" /> 
     <w:rFonts w:ascii="Arial" /> 
     <w:b /> 
     <w:sz w:val="28" /> 
    </w:rPr> 
    </w:style> 
</w:styles> 

回答

3

我認爲,這是因爲你是從頭開始創建一個新的文件,而不是立足您的文檔在模板上。我認爲默認樣式來自您的Normal.dotm模板(C:\Users\<userid>\AppData\Roaming\Microsoft\Templates),並且您需要根據您的文檔。我所做的是模板複製到文件的文件名和更改文件類型(從VB.NET未經測試的C#編譯):

public WordprocessingDocument CreateDocumentFromTemplate(string templateFileName, string docFileName) 
{ 
    File.Delete(docFileName); 
    File.Copy(templateFileName, docFileName); 
    var doc = WordprocessingDocument.Open(docFileName, true); 
    doc.ChangeDocumentType(WordprocessingDocumentType.Document); 
    return doc; 
} 

您的代碼將隨後是這樣的:

using (var doc = CreateDocumentFromTemplate(normalTemplatePath, tempPath)) 
{ 
    var stylePart = doc.MainDocumentPart.StyleDefinitionsPart; 
    ... 
} 

希望有所幫助!

+0

這就是我最終做的。我會將其標記爲答案。這麼晚纔回復很抱歉。 – DDA

相關問題