【问题标题】:Create New Empty Word Document创建新的空 Word 文档
【发布时间】:2014-02-20 06:19:59
【问题描述】:

我正在尝试使用 OpenXML SDK 2.5 创建一个空的 Word 文档 (DOCX)。以下代码对我不起作用,因为 MainDocumentPart 为空。

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

【问题讨论】:

    标签: c# openxml openxml-sdk


    【解决方案1】:

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

    【讨论】:

    • 谢谢,顺便试了一下没必要调用.Save();自创建以来
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多