Last post Jul 03, 2020 12:45 PM by Mayurib
Jul 02, 2020 12:45 PM|Mayurib|LINK
I want to replace placeholders in word doc with some text and I am using
OpenXmlPowerTools Regex method to achieve this. With this it successfully replaces placeholders in document contents but it is not replacing it if the same placeholder is present in header. I am not able to replace placeholders in
headers in the document. I searched for the HeaderParts and a method to replace placeholder from this headerpart but did not find any way. Please suggest how to do this.
Thanks in advance.
Jul 02, 2020 01:16 PM|asteranup|LINK
I have not tried it, but you can try something like-
using (StreamReader reader = new StreamReader(theDoc.MainDocumentPart.HeaderParts.First().GetStream()))
content = reader.ReadToEnd();
Regex exheadDate = new Regex("dataToReplace");
content = exheadDate.Replace(content, "Replacing text");
using (StreamWriter writer = new StreamWriter(theDoc.MainDocumentPart.HeaderParts.First().GetStream(FileMode.Create)))
Jul 02, 2020 02:23 PM|Mayurib|LINK
I think with this approach, it will not retain the formatting of the document. I don't want to disturb the style and formatting in the report as applying style and formatting to the document explicitly will be an additional overhead.
Jul 02, 2020 03:19 PM|asteranup|LINK
It should not alter the style of the document. Did you try it?
Jul 03, 2020 06:58 AM|yij sun|LINK
Accroding to your description,I have create a test and it works fine.Could you post your codes to us?It will help us to solve your problems.
You could refer to my codes:
Regex rex = new Regex(" ");
var src = Path.GetFullPath("C:\\Users\\yijings\\Desktop\\me.docx");
var doc = WordprocessingDocument.Open(src, true);
foreach (var part in doc.ContentParts())
var xdoc = part.GetXDocument();
var content = xdoc.Descendants(W.p);
OpenXmlRegex.Replace(content, rex,"rd" , null);
Jul 03, 2020 12:45 PM|Mayurib|LINK
Thank you Yijing Sun
It worked. Its replacing the placeholder in header. I changed the code little bit as per my document. But the approach is working.
Well, I have another issue. I am not able replace placeholders with images using OpenXmlPowerTools Regex or any other method. If you could suggest something on that as well that will be very helpful. The document
template I have contains placeholders for Images as well which should get replaced with one or more images.
I checked your response in other thread