C# OpenXML多行字符串替换(regex)显示为一条长线
我有一个docx文档,其中有“@Address”—我可以用以下内容替换:C# OpenXML多行字符串替换(regex)显示为一条长线,c#,ms-word,openxml,openxml-sdk,C#,Ms Word,Openxml,Openxml Sdk,我有一个docx文档,其中有“@Address”—我可以用以下内容替换: public static void SearchAndReplace(string document) { using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(document, true)) { string docText = null; using (StreamReader sr = new StreamReade
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("@Address");
docText = regexText.Replace(docText, multiLineString);
using (StreamWriter sw = new StreamWriter(wordDoc.MainDocumentPart.GetStream(FileMode.Create)))
{
sw.Write(docText);
}
}
}
这里有
问题是字符串在一行中返回
我是否做错了什么,或者是否有其他方法可以用多行文本替换我的文本?最简单的方法是用Break(
)字处理元素替换换行字符:
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("@Address");
string multiLineString = "Sample text.\nSample text.";
multiLineString = multiLineString.Replace("\r\n", "\n")
.Replace("\n", "<w:br/>");
docText = regexText.Replace(docText, multiLineString);
using (StreamWriter sw = new StreamWriter(wordDoc.MainDocumentPart.GetStream(FileMode.Create)))
sw.Write(docText);
}
}
publicstaticvoidsearchandreplace(字符串文档)
{
使用(WordprocessingDocument wordDoc=WordprocessingDocument.Open(document,true))
{
字符串docText=null;
使用(StreamReader sr=newstreamreader(wordDoc.MainDocumentPart.GetStream())
docText=sr.ReadToEnd();
Regex regexText=新的Regex(“@Address”);
string multiLineString=“示例文本。\n示例文本。”;
multiLineString=multiLineString.Replace(“\r\n”,“\n”)
.替换(“\n”和“);
docText=regexText.Replace(docText,多行线);
使用(StreamWriter sw=newstreamwriter(wordDoc.MainDocumentPart.GetStream(FileMode.Create)))
sw.Write(docText);
}
}
另外,请注意,还有一些其他特殊字符需要替换为相应的字处理元素。例如,
,
,
和
谢谢你,这对我帮助很大