使用OpenXML追加到DOCX文件



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

我认为你的代码中有问题,你正在使用tempDocText.ToString(),然后在for循环中初始化它,如下所示

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文件中添加文本,那么下面的代码可能会有所帮助。我在这里找到的。

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

相关内容

  • 没有找到相关文章