C# 将行附加到从 `*.dotx` 文件生成的 `*.docx` 文件

C# Append lines to `*.docx` file produced from `*.dotx` file

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

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

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

但是我得到这个错误:

Signature append failed:The process cannot access the file '(path)\destinationFile.docx' because it is being used by another process.

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

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

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