Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/kotlin/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用OpenXML将C#追加到DOCX文件_C#_.net_Stream_Openxml - Fatal编程技术网

使用OpenXML将C#追加到DOCX文件

使用OpenXML将C#追加到DOCX文件,c#,.net,stream,openxml,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.MainDo

我在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();
}
使用(WordprocessingDocument wordDoc=WordprocessingDocument.Open(wordFileNamePath,true))
{
for(int i=0;i

在第二个循环中,当涉及到
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
}

代码比我发布的要大,但是完整的代码不会有任何区别。正如您所说,应该在循环之前初始化tempDocText。“长度”也应该初始化。我的目标不是附加一个简单的文本,我需要附加一个xml(经过一些修改)。这个xml是从另一个DOCX文件中获取的,也许这会对您有所帮助。您提供的答案中的那个家伙没有附加内容,他做的和我在I=0时做的一样。然后,他关闭wordProcessingDocument并将其流保存为一个新的docx文件
if (i < length - 1)
{
    tempDocText = CreateNewStringBuilder(); //<-Initializing it here.
    InsertPageBreak(wordDoc);
}
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();
}