C#将行追加到`* .docx`文件生成的`* .docx`文件中

时间:2018-02-12 10:32:47

标签: c# openxml

我正在使用此代码从*.docx模板文件生成*.dotx文件:

从模板创建文档并替换字词:

Dictionary<string, string> keyValues = new Dictionary<string, string>();
keyValues.Add("xxxxReplacethat1", "replaced1");
keyValues.Add("xxxxReplacethat2", "replaced2");

File.Copy(sourceFile, destinationFile, true);

using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(destinationFile, true))
{
    // Change the document's type here
    wordDoc.ChangeDocumentType(WordprocessingDocumentType.Document);
    string docText = null;

    using (StreamReader sr = new StreamReader(wordDoc.MainDocumentPart.GetStream()))
    {
        docText = sr.ReadToEnd();
    }

    foreach (KeyValuePair<string, string> item in keyValues)
    {
        Regex regexText = new Regex(item.Key);
        docText = regexText.Replace(docText, item.Value);
    }

    using (StreamWriter sw = new StreamWriter(wordDoc.MainDocumentPart.GetStream(FileMode.Create)))
    {
        sw.Write(docText);
    }
    wordDoc.Close();
}

在另一个函数中,我试图将一些行附加到*.docx文件:

追加行:

foreach (var user in usersApproved)
                     File.AppendAllText(Server.MapPath(("..\\Files\\TFFiles\\" + tid + "\\" + file.SiteId + "\\" + file.Type + "\\")) + Path.GetFileName(file.Title), "Document Signed by: " + user.UserName + Environment.NewLine);

但是我收到了这个错误:

  

签名追加失败:进程无法访问该文件   '(path)\ destinationFile.docx'因为正在使用它   另一个过程。

也试过这个解决方案:OpenAndAddTextToWordDocument但我得到了同样的错误

1 个答案:

答案 0 :(得分:1)

这是使用“正则表达式”和“替换词典”替换文本的方法:

Dictionary<string, string> keyValues = new Dictionary<string, string>();
keyValues.Add("xxxxReplacethat1", "replaced1");
keyValues.Add("xxxxReplacethat2", "replaced2");

using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(destinationFile, true))
{
    // Change the document's type here
    wordDoc.ChangeDocumentType(WordprocessingDocumentType.Document);

    foreach (Run rText in wordDoc.MainDocumentPart.Document.Descendants<Run>())
    {
        foreach (var text in rText.Elements<Text>())
        {
            foreach (KeyValuePair<string, string> item in keyValues)
            {
                Regex regexText = new Regex(item.Key);
                text.Text = regexText.Replace(text.Text, item.Value);
            }
        }
    }
    wordDoc.Save();
}

这就是你追加文字的方式:

using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(destinationFile, true))
{
    var body = wordDoc.MainDocumentPart.Document.Body;

    var para = body.AppendChild(new Paragraph());
    var run = para.AppendChild(new Run());

    var txt = "Document Signed by: LocEngineer";
    run.AppendChild(new Text(txt));
    wordDoc.Save();
}