Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate docx from dotx without Microsoft Interop

Tags:

c#

I am using this code to replace 2 words and produce a *.doc (destinationFile) file from a *.dotx (sourceFile) file .

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

How I can modify this code to produce a *.docx because I need to append some lines to the *.docx file in another function.

I don't want to use Microsoft Interop because I don't want to install it on server.

like image 687
aggicd Avatar asked Oct 21 '25 15:10

aggicd


1 Answers

Did this myself a couple of weeks ago.

Copy the file first then open the copy and change it's document type

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();
}
like image 183
phuzi Avatar answered Oct 23 '25 04:10

phuzi