简体   繁体   中英

C# Append to DOCX file using OpenXML

I am using OpemXML in C# in order to build my DOCX file. My code looks like this:

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

On the second loop, when it comes to wordDoc.MainDocumentPart.GetStream(FileMode.Append, FileAccess.Write) I'm getting an ArgumentException saying "FileMode value is not supported."

I think there is a problem in your code, you are using tempDocText.ToString() before initializing it in the for loop as shown below

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
}

and Initializing it as in the later code block

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

Unless you provide more information about tempDocText , its dificult to help.

Anyways, if you just want to add text to a docx file then the following code may help. I found it 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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM