创建新的空Word文档

时间:2014-02-19 21:58:54

标签: c# openxml openxml-sdk

我正在尝试使用OpenXML SDK 2.5创建一个空Word文档(DOCX)。以下代码对我不起作用,因为MainDocumentPart为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);
            }
        }
    }

1 个答案:

答案 0 :(得分:8)

使用OpenXML类然后编写xml字符串要容易得多。试试这个:

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