我有一个带有“@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
问题是字符串是在一行中返回的。
我做错了什么或者是否有替代方法可以用多行文字替换我的文字?
答案 0 :(得分:0)
最简单的方法是使用Break(<w:br/>
)Wordprocessing元素替换换行符:
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);
}
}
另外,请注意还有一些其他特殊字符需要替换为相应的Wordprocessing元素
例如,<w:tab/>
,<w:noBreakHyphen/>
,<w:softHyphen/>
和<w:sym w:font="X" w:char="Y"/>
。