我正在使用C#中的以下功能来查找和替换使用Open XML SDK的Word文档。
// 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);
}
}
}
代码在大多数情况下都可以正常工作,但是在上面替换文本为“&”的情况下,打开文档时出错。
错误说:由于内容有问题,无法打开fileXYZ。详细信息:非法的名称字符。
当我在替换字符串中使用"<w:br/>"
在字符串末尾插入新行时,此错误也持续存在。但是我通过在"<w:br/> ".
PS:“替换文本”中带有注释。
// 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, new System.Xml.Linq.XText("Before *&* After").ToString()); // when we replace string with "&" we need to convert like this
using (StreamWriter sw = new StreamWriter(wordDoc.MainDocumentPart.GetStream(FileMode.Create)))
{
sw.Write(docText);
}
}
}