C#使用OpenXML附加到DOCX文件

时间:2013-04-16 18:23:57

标签: c# .net stream openxml

我在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值”。

1 个答案:

答案 0 :(得分:0)

我认为您的代码中存在问题,您在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();
}