0

Right now I'm exporting some text to a 2010 Word document. I have everything working except new lines. What is the character for a new line? I've tried "\r\n", " ^p ", and "\n", Nothing is working.

I'm using the "FindAndReplace" method to replace strings with strings.

The purpose for the newlines is some required formatting. My coworkers have a 6 line box that the text belongs in. On line 1 in that box I have "" and I'm replacing it with information from a database. If the information exceeds one line, they don't want the box to become 7 lines. So I've figured out how to calculate how many lines the text requires and I re-sized the box to 1 line. So for example if my string requires 2 lines, I want to put 4 blank lines after that.

If this is not possible, I was thinking of putting in that box: <line1> <line2> <line3> and so on... Then just replace each line individually. Any other thoughts? Thanks in advance.

Deduplicator
  • 44,692
  • 7
  • 66
  • 118
Charles Iams
  • 66
  • 1
  • 1
  • 8
  • [This link](http://stackoverflow.com/questions/2871887/inserting-newlines-in-word-using-openxml) maybe helpful, it adds newline using OpenXML. – Mahdi Tahsildari Dec 14 '12 at 16:50

3 Answers3

3

You can find each instance of new line with ^13 or (the equivalent) ^l and replace them with as many newlines as you require by concatenating ^13. The "Suchen und Ersetzen" dialog below is German for "Search and Replace". Tested in Word 2010.

Example:

Search and replace

This should work as is using COM automation with c#. An example link if you need one.

Here's proof of concept code:

namespace StackWord
{
    using StackWord = Microsoft.Office.Interop.Word;

    internal class Program
    {
        private static void Main(string[] args)
        {
            var myWord = new StackWord.Application { Visible = true };
            var myDoc = myWord.Documents.Add();
            var myParagraph = myDoc.Paragraphs.Add();
            myParagraph.Range.Text = 
               "Example test one\rExample two\rExample three\r";

            foreach (StackWord.Range range in myWord.ActiveDocument.StoryRanges)
            {
                range.Find.Text = "\r";
                range.Find.Replacement.Text = "\r\r\r\r";
                range.Find.Wrap = StackWord.WdFindWrap.wdFindContinue;
                object replaceAll = StackWord.WdReplace.wdReplaceAll;
                if (range.Find.Execute(Replace: ref replaceAll))
                {
                    Console.WriteLine("Found and replaced.");
                }
            }
            Console.WriteLine("Press any key to close...");
            Console.ReadKey();
            myWord.Quit();

        }
    }
}
Anthill
  • 1,219
  • 10
  • 20
2

You can always try using:

Environment.NewLine
mletterle
  • 3,968
  • 1
  • 24
  • 24
0

You save your file word to word 97 - 2003(*.doc), your "FindAndReplace" method will working :D