【发布时间】:2018-09-22 14:40:09
【问题描述】:
环境
Visual Studio 2017 C#(Word .docx 文件)
问题
查找/替换仅替换“{Today}” - 它无法替换“{ConsultantName}”字段。我检查了文档并尝试使用不同的方法(请参阅注释掉的代码),但没有任何乐趣。
Word 文档只有几段文本 - 文档中没有表格或文本框。我做错了什么?
更新
当我检查 doc_text 字符串时,我可以看到“{Today}”,但“{ConsultantName}”被拆分为多个运行。左大括号和右大括号不和单词在一起——它们之间有 XML 标记:
{</w:t></w:r><w:proofErr w:type="spellStart"/><w:r w:rsidR="00544806"><w:t>ConsultantName</w:t></w:r><w:proofErr w:type="spellEnd"/><w:r w:rsidR="00544806"><w:t>}
代码
string doc_text = string.Empty;
List<string> s_find = new List<string>();
List<string> s_replace = new List<string>();
// Regex regexText = null;
s_find.Add("{Today}");
s_replace.Add("24 Sep 2018");
s_find.Add("{ConsultantName}");
s_replace.Add("John Doe");
using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(filePath, true))
{
// read document
using (StreamReader sr = new StreamReader(wordDoc.MainDocumentPart.GetStream()))
{
doc_text = sr.ReadToEnd();
}
// find replace
for (byte b = 0; b < s_find.Count; b++)
{
doc_text = new Regex(s_find[b], RegexOptions.IgnoreCase).Replace(doc_text, s_replace[b]);
// regexText = new Regex(s_find[b]);
// doc_text = doc_text.Replace(s_find[b], s_replace[b]);
// doc_text = regexText.Replace(doc_text, s_replace[b]);
}
// update document
using (StreamWriter sw = new StreamWriter(wordDoc.MainDocumentPart.GetStream(FileMode.Create)))
{
sw.Write(doc_text);
}
}
【问题讨论】: