我需要在文档中搜索 中包含的字符串。因此,如果应用程序在文档中找到该变量,它将用 DateTime.Today.ToShortDateString() 替换该变量。例如:
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>
。谁能帮我吗?
对于任何仍在为此苦苦挣扎的人 - 你可以查看这个库
https://github.com/antonmihaylov/OpenXmlTemplates https://github.com/antonmihaylov/OpenXmlTemplates
使用它,您不必在文本中搜索特殊标签(因为 Thomas Barnekow 的评论中指定的问题),而是在文档中添加一个内容控件,并在内容控件的标签名称中指定您想要的变量的名称。想要更换。
然后,您可以提供 JSON 数据或常规 C# 字典对象,文本将被替换。
注意 - 我是该库的创建者,但我没有从中获得经济收益 - 它是开源的并且正在积极开发中(并且一直在寻找贡献者!)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)