![](/img/trans.png)
[英]OpenXML SDK add line break or use multiline string in replace (regex)
[英]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/zh-cn/library/office/bb508261.aspx
問題是字符串在一行中返回。
我是在做錯什么嗎?還是可以使用多行文字替換我的文字?
最簡單的方法是用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"/>
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.