OpenXML 多行字符串替换(正则表达式)显示为一长行
OpenXML multiline string replace (regex) showing as one long line
我有一个带有“@Address”的 docx 文档-我可以用这个替换它:
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);
}
}
}
此处可用https://msdn.microsoft.com/en-us/library/office/bb508261.aspx
问题是字符串在一行中返回。
我是不是做错了什么,或者是否有其他方法可以用来将我的文本替换为多行文本?
最简单的方法是将换行符替换为 Break (<w:br/>
) 文字处理元素:
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);
}
}
另请注意,还有一些其他特殊字符需要替换为相应的文字处理元素。
例如,<w:tab/>
、<w:noBreakHyphen/>
、<w:softHyphen/>
和 <w:sym w:font="X" w:char="Y"/>
。
我有一个带有“@Address”的 docx 文档-我可以用这个替换它:
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);
}
}
}
此处可用https://msdn.microsoft.com/en-us/library/office/bb508261.aspx
问题是字符串在一行中返回。
我是不是做错了什么,或者是否有其他方法可以用来将我的文本替换为多行文本?
最简单的方法是将换行符替换为 Break (<w:br/>
) 文字处理元素:
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);
}
}
另请注意,还有一些其他特殊字符需要替换为相应的文字处理元素。
例如,<w:tab/>
、<w:noBreakHyphen/>
、<w:softHyphen/>
和 <w:sym w:font="X" w:char="Y"/>
。