我在 C# 中使用以下函数使用 open xml sdk 在 word doc 中查找和替换。
// To search and replace content in a document part.
public static void SearchAndReplace(string document)
{
using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(document, true))
{
string docText = null;
using (StreamReader sr = new StreamReader(wordDoc.MainDocumentPart.GetStream()))
{
docText = sr.ReadToEnd();
}
Regex regexText = new Regex("Findme");
docText = regexText.Replace(docText, "Before *&* After"); // <-- Replacement text
using (StreamWriter sw = new StreamWriter(wordDoc.MainDocumentPart.GetStream(FileMode.Create)))
{
sw.Write(docText);
}
}
}
代码在大多数情况下都可以正常工作,但在上面替换文本有“&”的情况下,打开文档时会出错..
错误说:文件XYZ无法打开,因为内容有问题。详细信息:非法名称字符。
"<w:br/>"
当我在替换字符串中使用以在字符串末尾插入新行时,此错误也仍然存在 。但是我通过在之后添加一个空格来消除错误"<w:br/> ".
PS:“替换文本”在注释中注明。