Create New Empty Word Document
Asked Answered
F

1

7

I'm trying to create an empty Word document (DOCX) using OpenXML SDK 2.5. The following code is not working for me because MainDocumentPart is null.

    public static void CreateEmptyDocxFile(string fileName, bool overrideExistingFile)
    {
        if (System.IO.File.Exists(fileName))
        {
            if (!overrideExistingFile)
                return;
            else
                System.IO.File.Delete(fileName);
        }

        using (WordprocessingDocument document = WordprocessingDocument.Create(fileName, WordprocessingDocumentType.Document))
        {
            const string docXml =
         @"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?> 
            <w:document xmlns:w=""http://schemas.openxmlformats.org/wordprocessingml/2006/main"">
                <w:body>
                    <w:p>
                        <w:r>
                            <w:t></w:t>
                        </w:r>
                    </w:p>
                </w:body>
            </w:document>";

            using (Stream stream = document.MainDocumentPart.GetStream())
            {
                byte[] buf = (new UTF8Encoding()).GetBytes(docXml);
                stream.Write(buf, 0, buf.Length);
            }
        }
    }
Floozy answered 19/2, 2014 at 21:58 Comment(0)
D
18

It is much easier to use OpenXML classes then writing xml string. Try this:

using (WordprocessingDocument document = WordprocessingDocument.Create(fileName, WordprocessingDocumentType.Document))
{
    MainDocumentPart mainPart = document.AddMainDocumentPart();
    mainPart.Document = new Document(new Body());
    //... add your p, t, etc using mainPart.Document.Body.AppendChild(...);

    //seems like there is no need in this call as it is a creation process
    //document.MainDocumentPart.Document.Save();
}
Deme answered 19/2, 2014 at 22:9 Comment(2)
Thank you, by the way I tried it there is no need to call .Save(); since it's creationFloozy
I needed these three usings to get this code to work: using DocumentFormat.OpenXml; using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Wordprocessing;Messina

© 2022 - 2024 — McMap. All rights reserved.