openxml-sdk - 使用settings.xml创建word 2007文件

时间:2011-05-20 18:23:24

标签: c# ms-word openxml-sdk openxml

我正在尝试使用以下代码生成新的Word文档。生成Word文档时没有settings.xml。我需要在word文件中有settings.xml。任何帮助将不胜感激。

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;
}

1 个答案:

答案 0 :(得分: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();
    }