我在运行时将一些包含'\ r \ n'的文本附加到word文档中。 但当我看到word文档时,它们被替换为小方框: - (
我尝试用System.Environment.NewLine
替换它们,但我仍然看到这些小盒子。
有什么想法吗?
答案 0 :(得分:4)
你是不是孤立地尝试了一个或另一个,即{。{1}}或\r
,因为Word将分别解释回车和换行。您唯一一次使用Environment.Newline是纯ASCII文本文件。 Word将以不同方式处理这些字符!甚至是Ctrl + M序列。试试这个,如果它不起作用,请发布代码。
答案 1 :(得分:4)
答案是使用\v
- 这是段落。
答案 2 :(得分:0)
Word使用<w:br/>
XML元素进行换行。
答案 3 :(得分:0)
经过多次试验和错误,这里有一个函数可以设置Word XML节点的文本,并处理多行:
//Sets the text for a Word XML <w:t> node
//If the text is multi-line, it replaces the single <w:t> node for multiple nodes
//Resulting in multiple Word XML lines
private static void SetWordXmlNodeText(XmlDocument xmlDocument, XmlNode node, string newText)
{
//Is the text a single line or multiple lines?>
if (newText.Contains(System.Environment.NewLine))
{
//The new text is a multi-line string, split it to individual lines
var lines = newText.Split("\n\r".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
//And add XML nodes for each line so that Word XML will accept the new lines
var xmlBuilder = new StringBuilder();
for (int count = 0; count < lines.Length; count++)
{
//Ensure the "w" prefix is set correctly, otherwise docFrag.InnerXml will fail with exception
xmlBuilder.Append("<w:t xmlns:w=\"http://schemas.microsoft.com/office/word/2003/wordml\">");
xmlBuilder.Append(lines[count]);
xmlBuilder.Append("</w:t>");
//Not the last line? add line break
if (count != lines.Length - 1)
{
xmlBuilder.Append("<w:br xmlns:w=\"http://schemas.microsoft.com/office/word/2003/wordml\" />");
}
}
//Create the XML fragment with the new multiline structure
var docFrag = xmlDocument.CreateDocumentFragment();
docFrag.InnerXml = xmlBuilder.ToString();
node.ParentNode.AppendChild(docFrag);
//Remove the single line child node that was originally holding the single line text, only required if there was a node there to start with
node.ParentNode.RemoveChild(node);
}
else
{
//Text is not multi-line, let the existing node have the text
node.InnerText = newText;
}
}