C#-从没有Microsoft Interop的dotx生成docx

我正在使用此代码替换2个单词,并从* .dotx(sourceFile)文件生成一个* .doc(destinationFile)文件.

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

我如何修改此代码以生成* .docx,因为我需要在另一个函数中向* .docx文件添加一些行.

我不想使用Microsoft Interop,因为我不想在服务器上安装它.

最佳答案
几周前我自己做了这个.

首先复制文件,然后打开副本并更改其文档类型

var template = @"SourceTemplate.dotx";
var destinationFile = @"DestinationFile.docx";

File.Copy(template, destinationFile);
using (WordprocessingDocument document = WordprocessingDocument.Open(destinationFile, true)) {

    // Change the document's type here
    document.ChangeDocumentType(WordprocessingDocumentType.Document);

    // Do any additional processing here

    document.Close();
}

转载注明原文:C#-从没有Microsoft Interop的dotx生成docx - 代码日志