3
votes

I'm updating a word document by rewriting the CustomXMLPart file. I've basically followed this tutorial: http://blogs.msdn.com/b/brian_jones/archive/2009/01/05/taking-advantage-of-bound-content-controls.aspx

private bool _makeDoc()
        {

        var path = HttpContext.Current.Server.MapPath("~/Classes/Word/template.docx");
        using (WordprocessingDocument myDoc = WordprocessingDocument.Open(path, true))
        {
            //create new XML string
            //these values will populate the template word doc
            string newXML = "<root>";
                newXML += "<name>";
                newXML += "name goes here";
                newXML += "</name>";
                newXML += "<bio>";
                newXML += "text" + "more text";
                newXML += "</bio>";
            newXML += "</root>";

            MainDocumentPart mainPart = myDoc.MainDocumentPart;

            //delete old xml part
            mainPart.DeleteParts<CustomXmlPart>(mainPart.CustomXmlParts);

            //add new xml part
            CustomXmlPart customXml = mainPart.AddCustomXmlPart(CustomXmlPartType.CustomXml);
            using(StreamWriter ts = new StreamWriter(customXml.GetStream()))
            {
                ts.Write(newXML);
            }
            myDoc.Close();
        }
        return true;
    }

The problem is that I can't figure out how to add a line break between "text" and "more text". I've tried Environment.NewLine, I've tried wrapping it in <w:p><w:r><w:t> tags. I can't seem to get it to produce a valid docx file.

Any help would be appreciated.

3

3 Answers

3
votes

The Content Control properties has an option for "Allow carriage returns". Turning this on, and using Environment.NewLine worked perfectly.

1
votes

I believe you'll have to wrap them in paragraphs in order to get the returns, as far as I know at least. So your resulting OOXML would look something like,

<w:p><w:r><w:t>Text</w:t></w:r></w:p>
<w:p><w:r><w:t>More text</w:t></w:r></w:p>

As far as it not resulting in valid OOXML when you do this, have you opened the OOXML package "document.xml" and saw exactly where the XML is invalid?

Edit:

The OOXML SDK 2.0 comes with some validation tools you might find useful.

0
votes

via raw XML you can add:

<w:r>
    <w:br />
  </w:r>

via OOXML SDK:

Paragraph paragraph1 = new Paragraph();
Run breakRun = new Run();
breakRun.Append( new Break() );
paragraph1.Append( breakRun );

_document.MainDocumentPart.Document.AppendChild<Paragraph>(paragraph1);
//where _document is the WordProcessingDocument instance