3

我在运行时将一些包含 '\r\n' 的文本附加到 word 文档中。但是当我看到word文档时,它们被替换为小方块:-(

我尝试用它们替换它们,System.Environment.NewLine但我仍然看到这些小盒子。

任何想法?

4

4 回答 4

8

答案是使用\v- 这是一个段落中断。

于 2010-12-22T22:48:36.117 回答
4

您是否没有单独尝试过一种或另一种,即\rWord\n将分别解释回车和换行。唯一一次使用 Environment.Newline 是在纯 ASCII 文本文件中。Word 会以不同的方式处理这些字符!甚至是 Ctrl+M 序列。尝试一下,如果它不起作用,请发布代码。

于 2009-12-21T14:00:58.883 回答
0

Word 使用<w:br/>XML 元素进行换行。

于 2014-12-18T06:39:44.067 回答
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;
    }
}
于 2015-01-16T12:30:38.030 回答