简体   繁体   中英

nvarchar(max) from SQL Server DB to XML Word Doc not preserving carriage return

I have written a program that would pick up information from a SQL Server table and put the information into MS WORD.

foreach (String note in doc_object.alJobNotes)
{
    String formattednote = "";
    newTextElement = xdoc.CreateElement("w:t", wordmlNamespace);
    formattednote = note.Replace(Environment.NewLine, "
");
    XmlText newText = xdoc.CreateTextNode(formattednote);
    newTextElement.AppendChild(newText);
    XmlAttribute xmlSpace = xdoc.CreateAttribute(
                        "xml", "space",
                        "http://www.w3.org/XML/1998/namespace");
    xmlSpace.Value = "preserve";
    newTextElement.Attributes.Append(xmlSpace);
    ChildNode.ParentNode.InsertAfter(newTextElement, ChildNode);
    EmptyElement = xdoc.CreateElement("w:br", wordmlNamespace);

    EmptyElement.Attributes.Append(xmlSpace);

    ChildNode.ParentNode.InsertAfter(EmptyElement, ChildNode);
    ChildNode.ParentNode.InsertAfter(EmptyElement, ChildNode);
    ChildNode.ParentNode.InsertAfter(EmptyElement, ChildNode);
    ChildNode.ParentNode.InsertAfter(EmptyElement, ChildNode);
}

However, when I open Ms Word, the places where the carriage return is meant to be just shows 

I have tried replacing it with &#10; , (char)13 , (char)10 , <br/> , <w:cr> but I cannot find how to do it.

Any suggestions please?

Well, if I'm correctly interpreting your code and the problem description I believe the issue is that you're not generating valid WordOpenXML. (I'm assuming this is the docx file format!)

Take a look at the raw XML your code emits and compare it with a sample Word document's document.xml file in the ZIP package.

It appears your code is appending the new line as part of the w:t element. But that's not how WordOpenXML is designed. WordOpenXML is more like this where w:p is the paragraph ("carriage return" / ANSI 13):

<w:p>
  <w:r>
     <w:t>text here</w:t>
  </w:r>
</w:p>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM