我在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);
}
}
}
代码适用于大多数情况,但上面的情况替换文本有“&amp;”打开文档时出错..
错误说:由于内容有问题,无法打开fileXYZ。 细节:非法名称字符。
当我在替换字符串中使用"<w:br/>"
在字符串末尾插入新行时,此错误也会持续存在。但我通过在"<w:br/> ".
PS:“替换文字”用注释表示。
答案 0 :(得分:1)
// 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);
}
}
}