开发者

openxml-sdk - Creating word 2007 file with settings.xml

I am trying to generate a new Word document using the following code. The Word document gets generated without settings.xml. I need to have settings.xml in the word file. Any help would be appreciated.

public static byte[] GenerateNewDocument()
{
    byte[] returnValue = null;
    MemoryStream stream = null;
    WordprocessingDocument开发者_如何学JAVA 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;
}


You need to create your own DocumentSettingsPart and then insert it into the MainDocumentPart. So the settings part may look like this:

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

And then having that saved somewhere as "settings.xml", you could use code like this:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜