OpenXML在Word文档中查找变量并将其替换 [英] OpenXML Find Variables within Word doc and replace them
问题描述
我需要在文档中搜索<>中包含的字符串.因此,如果应用程序在文档中找到该变量,它将用DateTime.Today.ToShortDateString()替换该变量.例如:
I need to search a document for strings enclosed in <>. So if the application finds the variable within the document, it replaces that variable with DateTime.Today.ToShortDateString(). For instance:
string filename = "C:\\Temp\\" + appNum + "_ReceiptOfApplicationLtr.docx";
if (File.Exists((string)filename))
{
using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(filename, true))
{
var body = wordDoc.MainDocumentPart.Document.Body;
foreach (var text in body.Descendants<Text>())
{
if (text.Text == "<TodaysDate>")
{
text.Text = text.Text.Replace("<TodaysDate>", DateTime.Today.ToShortDateString());
}
}
using (StreamWriter sw = new StreamWriter(wordDoc.MainDocumentPart.GetStream(FileMode.Create)))
{
sw.Write(filename);
}
}
}
当搜索后代文本时,它会找到第一个< ;,然后是TodaysDate,最后是>.问题是找不到字符串<TodaysDate>
.有人可以帮我吗?
Well when it searches the Descendants Text, it finds the first <, then TodaysDate, finally >. The issue being it won't find the string <TodaysDate>
. Can anyone help me out?
推荐答案
Open XML可以在同一运行中将文本存储在不同的text
标记中.如果您是我,该怎么办就是找到存储字符串的Run
并使用InnerText
属性查找该运行中的所有文本.
例如:
Open XML can store text in different text
tags inside the same run. What I would do if I were you is just find the Run
where your string is stored and use the InnerText
property to find all the text inside that run.
For example:
Run runToFind = body.Descendants<Run>()
.FirstOrDefault(r => r.Innertext.Contains("<TodaysDate>");
然后您可以将Run
替换为另一个:
Then you can replace the Run
with another one:
runToFind.Parent.Replace(new Run(new Text(DateTime.Now.ToShortDateString())),runToFind);
这篇关于OpenXML在Word文档中查找变量并将其替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!