2011-05-20 70 views
3

我正在嘗試使用以下代碼生成新的Word文檔。 Word文檔在沒有settings.xml的情況下生成。我需要在word文件中有settings.xml。任何幫助,將不勝感激。openxml-sdk - 使用settings.xml創建word 2007文件

public static byte[] GenerateNewDocument() 
{ 
    byte[] returnValue = null; 
    MemoryStream stream = null; 
    WordprocessingDocument wordDoc = null; 

    try 
    { 
     stream = new System.IO.MemoryStream(); 
     wordDoc = WordprocessingDocument.Create(stream, WordprocessingDocumentType.Document); 
    } 
    catch 
    { 
     if (stream != null) 
     { 
      stream.Close(); 
     } 

     throw; 
    } 

    using (wordDoc) 
    { 
     wordDoc.AddMainDocumentPart(); 
     MainDocumentPart mainPart = wordDoc.MainDocumentPart; 
     mainPart.Document = new Document(new Body());    
     mainPart.Document.Save(); 
    } 

    returnValue = stream.ToArray(); 
    return returnValue; 
} 

回答

4

您需要創建自己的DocumentSettingsPart,然後將其插入MainDocumentPart。因此,設置的一部分可能是這樣的:

<w:settings xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:m="http://schemas.openxmlformats.org/officeDocument/2006/math" xmlns:v="urn:schemas-microsoft-com:vm" xmlns:w10="urn:schemas-microsoft-com:office:word" xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:sl="http://schemas.openxmlformats.org/schemaLibrary/2006/main"> 
<w:defaultTabStop w:val="475"/> 
<w:compat> 
<w:compatSetting w:name="compatibilityMode" w:uri="http://schemas.microsoft.com/office/word" w:val="14"/> 
</w:compat> 
</w:settings> 

然後在某個地方保存爲「的settings.xml」有,你可以使用這樣的代碼:

private static void AddSettingsToMainDocumentPart(MainDocumentPart part) 
    { 
     DocumentSettingsPart settingsPart = part.AddNewPart<DocumentSettingsPart>(); 
     FileStream settingsTemplate = new FileStream("settings.xml", FileMode.Open, FileAccess.Read); 
     settingsPart.FeedData(settingsTemplate); 
     settingsPart.Settings.Save(); 
    } 
+0

莫非settings.xml中的內容在一個局部變量中,並且可以使用它? – 2011-05-20 18:54:41

+0

是的,它可以是預製的,例如我上面給出的例子,也可以使用零件的成員動態創建,例如http://msdn.microsoft.com/en-us/library/ documentformat.openxml.packaging.documentsettingspart_members.aspx。 – 2011-05-22 01:08:59

+0

宅男,謝謝。我已經使用了這種方法,並且可行。你能幫我在這個問題以及 - http://stackoverflow.com/questions/5877182/open-xml-using-stylepaneformatfilter-attribute-to-show-normal-style-along-wit – 2011-05-22 04:20:08