【问题标题】:C# Append to DOCX file using OpenXMLC# 使用 OpenXML 附加到 DOCX 文件
【发布时间】:2013-04-16 18:23:57
【问题描述】:

我在 C# 中使用 OpemXML 来构建我的 DOCX 文件。我的代码如下所示:

using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(wordFileNamePath, true))
{
    for (int i = 0; i < length; i++)
    {
        using (StreamWriter sw = new StreamWriter(i == 0 ? wordDoc.MainDocumentPart.GetStream(FileMode.Create) : wordDoc.MainDocumentPart.GetStream(FileMode.Append, FileAccess.Write)))
        {
            sw.Write(tempDocText.ToString());
        }
        if (i < length - 1)
        {
            tempDocText = CreateNewStringBuilder();
            InsertPageBreak(wordDoc);
        }
    }
    wordDoc.MainDocumentPart.Document.Save();
}

在第二个循环中,当涉及到 wordDoc.MainDocumentPart.GetStream(FileMode.Append, FileAccess.Write) 时,我收到一个 ArgumentException,说“不支持 FileMode 值”。

【问题讨论】:

    标签: c# .net stream openxml


    【解决方案1】:

    我认为您的代码有问题,您在 for 循环中初始化之前使用 tempDocText.ToString(),如下所示

    using (StreamWriter sw = new StreamWriter(i == 0 ? wordDoc.MainDocumentPart.GetStream(FileMode.Create) : wordDoc.MainDocumentPart.GetStream(FileMode.Append, FileAccess.Write)))
    {
        sw.Write(tempDocText.ToString()); //<-Used before Initialization
    }
    

    并在后面的代码块中初始化它

    if (i < length - 1)
    {
        tempDocText = CreateNewStringBuilder(); //<-Initializing it here.
        InsertPageBreak(wordDoc);
    }
    

    除非您提供有关 tempDocText 的更多信息,否则很难提供帮助。

    无论如何,如果您只想将文本添加到 docx 文件,那么以下代码可能会有所帮助。我找到了here

    public static void OpenAndAddTextToWordDocument(string filepath, string txt)
    {   
        // Open a WordprocessingDocument for editing using the filepath.
        WordprocessingDocument wordprocessingDocument = 
            WordprocessingDocument.Open(filepath, true);
    
        // Assign a reference to the existing document body.
        Body body = wordprocessingDocument.MainDocumentPart.Document.Body;
    
        // Add new text.
        Paragraph para = body.AppendChild(new Paragraph());
        Run run = para.AppendChild(new Run());
        run.AppendChild(new Text(txt));
    
        // Close the handle explicitly.
        wordprocessingDocument.Close();
    }
    

    【讨论】:

    • 代码比我发布的要大,但完整的代码不会有任何区别。正如你所说,初始化 tempDocText 应该在循环之前进行。 'length' 也应该被初始化。我的目标不是附加一个简单的文本,我需要附加一个 xml(经过一些修改)。此 xml 取自另一个 DOCX 文件
    • 那么也许这个answer会帮助你
    • 您提供的答案中的那个人没有附加,他正在做我在 i = 0 时所做的事情。然后他关闭 wordProcessingDocument 并保存他的流做一个新的 docx 文件
    猜你喜欢
    • 2013-04-10
    • 2012-03-05
    • 1970-01-01
    • 1970-01-01
    • 2014-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多