It's my first time using DocumentFormat.OpenXml so I have a noob question/problem.
Using help from this post: Save modified WordprocessingDocument to new file I wrote the code below to change some text (by tag) in an existing Word (.docx) document and then download as a new file.
I'm using Asp.Net Core 3.1 for a small web application.
byte[] result;
//source file
var path = Path.Combine(_webHostingEnvironment.WebRootPath, "templates\\MyReport.docx");
string documentText;
byte[] byteArray = System.IO.File.ReadAllBytes(path);
using (MemoryStream stream = new MemoryStream())
{
stream.Write(byteArray, 0, (int)byteArray.Length);
using (WordprocessingDocument doc = WordprocessingDocument.Open(stream, true))
{
using (StreamReader reader = new StreamReader(doc.MainDocumentPart.GetStream()))
{
documentText = reader.ReadToEnd();
}
documentText = documentText.Replace("company", "My Company ltd.");
}
result = stream.ToArray();
}
//download new file
return File(result, "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "MyReport.docx");
I'm experiencing two problems:
- file downloaded is exactly the same as the source Word file.
documentText.Replace
seems to have no effect on the file being downloaded - when I want to use a bit more "complex" tags within the source Word file, e.g.
{company}
it gets "split" in thedocumentText
into separate words...
What am I doing wrong?