openXmlSdk insert new line inside of a Run Element

前端 未结 1 1024
你的背包
你的背包 2021-01-28 22:23

I have text inside of the Run Element. I\'m trying to replace the \\r in the string with a line break.

The text as follows

<
1条回答
  •  被撕碎了的回忆
    2021-01-28 22:49

    The documentation states that a Text element contains literal text. The SDK will not make assumptions about new line characters in a string that you write to a Text element. How would it know if you wanted a break or if you wanted a paragraph?

    If you are building the document from literal strings you will have some work to do:

    using DocumentFormat.OpenXml;
    using DocumentFormat.OpenXml.Packaging;
    using DocumentFormat.OpenXml.Wordprocessing;
    
    namespace OXmlTest
    {
        class Program
        {
            static void Main(string[] args)
            {
                using (var wordDocument = WordprocessingDocument
                    .Create("c:\\deleteme\\testdoc.docx", WordprocessingDocumentType.Document))
                {
                    MainDocumentPart mainPart = wordDocument.AddMainDocumentPart();
    
                    mainPart.Document = new Document();
                    Body body = mainPart.Document.AppendChild(new Body());
                    Paragraph p = body.AppendChild(new Paragraph());                
                    Run r = p.AppendChild(new Run());
    
                    string theString = "This is an example project for testing purposes. \rThis is all sample data, none of this is real information. \r\rThis field allows for the entry of more information, a larger text field for example purposes";
    
                    foreach (string s in theString.Split(new char[] { '\r' }))
                    {
                        r.AppendChild(new Text(s));
                        r.AppendChild(new Break());
                    }
    
                    wordDocument.Save();
                }
            }
        }
    }
    

    
    
        
            
                
                    This is an example project for testing purposes. 
                    
                    This is all sample data, none of this is real information. 
                    
                    
                    
                    This field allows for the entry of more information, a larger text field for example purposes
                    
                
            
        
    
    

    0 讨论(0)
提交回复
热议问题