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.
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With