在没有Microsoft Interop的情况下从dotx生成docx

时间:2018-02-12 09:09:42

标签: c#

我使用此代码替换2个单词并从*.doc(sourceFile)文件生成*.dotx(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,因为我不想在服务器上安装它。

1 个答案:

答案 0 :(得分:3)

几周前我自己做过这件事。

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

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