Microsoft Office Forums Unable to insert line break or carriage return in mail merge field

Go Back   Microsoft Office Forums > >

Reply
 
Thread Tools Display Modes
  #1  
Old 09-11-2019, 03:03 AM
shahid.majeed shahid.majeed is online now Unable to insert line break or carriage return in mail merge field Windows 10 Unable to insert line break or carriage return in mail merge field Office 2013
Novice
Unable to insert line break or carriage return in mail merge field
 
Join Date: Sep 2019
Posts: 3
shahid.majeed is on a distinguished road
Default Unable to insert line break or carriage return in mail merge field

Hi,



I have word template document having some merge fields. One merge field have multiple values which i want to show each value with line break.

For example:
Value1
Value2
Value3

Here is my code, when document is created and download values are not shows with line break they shows with whitespace between them.


Code:
 private void setupDocument()
    {
        try
        {
            string documentLanguage = language.Equals("English") ? "English" : "Swedish";
            docName = "~/Media/bookingDocs/" + documentLanguage + "_Doc_" + bookingID + ".docx";
            string generatedFile = HttpContext.Current.Server.MapPath(docName);
            File.Copy(getTemplateFilePath(), generatedFile, true);
            Dictionary<string, string> keyValues = new Dictionary<string, string>();
            keyValues.Add("MainRoomName", doc.MainRoom);
            keyValues.Add("BookingStartEndTime", doc.BookingTime);
            keyValues.Add("TotalGuest", doc.TotalGuest);
            keyValues.Add("BreakfastServingTime", doc.BreakfastServingTime);
            keyValues.Add("LunchServingTime", doc.LunchServingTime);
            keyValues.Add("CoffeServingTime", doc.CoffeServingTime);
            keyValues.Add("CompanyName", doc.CompanyName);

            using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(generatedFile, true))
            {
                var mergeFields = wordDoc.MainDocumentPart.RootElement.Descendants<FieldCode>();
                foreach (KeyValuePair<string, string> keys in keyValues)
                {
                    ReplaceMergeFieldWithText(mergeFields, keys.Key, keys.Value);
                }

                // update lunch room merge field
                ReplaceMergeFieldLunchRooms(mergeFields, "LunchRoomName", doc.ListOfLunchRooms);
                // update mergeField for specialFood
                ReplaceMergeFieldSpecialFood(mergeFields, "BookingSpecialFoodList", doc.ListOfSpecialFood);

                wordDoc.MainDocumentPart.Document.Save();
            }
        }
        catch (Exception exc)
        {
            log.Error(userName + ": Exception in preparePrintDocument setupDocument: " + exc.Message);
            log.Error(userName + ": Exception in preparePrintDocument setupDocument: " + exc.StackTrace);
            throw new Exception(exc.Message);
        }
    }
    private void ReplaceMergeFieldLunchRooms(IEnumerable<FieldCode> fields, string mergeFieldName, List<System.Web.UI.WebControls.ListItem> lunchRoomList)
    {
        try
        {
            var field = fields
                .Where(f => f.InnerText.Contains(mergeFieldName))
                .FirstOrDefault();

            if (field != null)
            {
                // Get the Run that contains our FieldCode
                // Then get the parent container of this Run
                Run rFldCode = (Run)field.Parent;

                // Get the three (3) other Runs that make up our merge field
                Run rBegin = rFldCode.PreviousSibling<Run>();
                Run rSep = rFldCode.NextSibling<Run>();
                Run rText = rSep.NextSibling<Run>();
                Run rEnd = rText.NextSibling<Run>();

                // Get the Run that holds the Text element for our merge field
                // Get the Text element and replace the text content 
                Text t = rText.GetFirstChild<Text>();
                System.Text.StringBuilder sb = new StringBuilder();
                if (lunchRoomList.Count > 0)
                {
                    foreach (System.Web.UI.WebControls.ListItem item in lunchRoomList)
                    {
                        sb.Append(item.Text);
                        sb.Append(Environment.NewLine); 
                    }
                }
                t.Text = sb.ToString();

                // Remove all the four (4) Runs for our merge field
                rFldCode.Remove();
                rBegin.Remove();
                rSep.Remove();
                rEnd.Remove();
            }
        }
        catch (Exception exc)
        {
            log.Error(userName + ": Exception in preparePrintDocument ReplaceMergeFieldWithText: " + exc.Message);
            log.Error(userName + ": Exception in preparePrintDocument ReplaceMergeFieldWithText: " + exc.StackTrace);
            throw new Exception(exc.Message);
        }
    }
Reply With Quote
  #2  
Old 09-17-2019, 09:56 PM
macropod's Avatar
macropod macropod is offline Unable to insert line break or carriage return in mail merge field Windows 7 64bit Unable to insert line break or carriage return in mail merge field Office 2010 32bit
Administrator
 
Join Date: Dec 2010
Location: Canberra, Australia
Posts: 19,541
macropod is a splendid one to beholdmacropod is a splendid one to beholdmacropod is a splendid one to beholdmacropod is a splendid one to beholdmacropod is a splendid one to beholdmacropod is a splendid one to beholdmacropod is a splendid one to beholdmacropod is a splendid one to behold
Default

It's not apparent to me why you'd be creating the document from scratch every time instead of using a document or template with the required fields already in place. That would require much less code and would be far easier to maintain.

As for changing a mergefield's output from:
Value1 Value2 Value3
to:
Value1
Value2
Value3
there is no mergefield coding that can produce such a result.
__________________
Cheers,
Paul Edstein
[MS MVP - Word]
Reply With Quote
  #3  
Old Yesterday, 04:03 AM
shahid.majeed shahid.majeed is online now Unable to insert line break or carriage return in mail merge field Windows 10 Unable to insert line break or carriage return in mail merge field Office 2013
Novice
Unable to insert line break or carriage return in mail merge field
 
Join Date: Sep 2019
Posts: 3
shahid.majeed is on a distinguished road
Default

Hi macropod,
Thanks for the replay. basically i am create a document for events. So i have template doc with merge field. Which will be replace with actual information and new document is save for the event. each event have different information so document should be created from the scrach for the each event.
Reply With Quote
  #4  
Old Yesterday, 03:49 PM
macropod's Avatar
macropod macropod is offline Unable to insert line break or carriage return in mail merge field Windows 7 64bit Unable to insert line break or carriage return in mail merge field Office 2010 32bit
Administrator
 
Join Date: Dec 2010
Location: Canberra, Australia
Posts: 19,541
macropod is a splendid one to beholdmacropod is a splendid one to beholdmacropod is a splendid one to beholdmacropod is a splendid one to beholdmacropod is a splendid one to beholdmacropod is a splendid one to beholdmacropod is a splendid one to beholdmacropod is a splendid one to behold
Default

Quote:
Originally Posted by shahid.majeed View Post
basically i am create a document for events. So i have template doc with merge field. Which will be replace with actual information and new document is save for the event. each event have different information so document should be created from the scrach for the each event.
But your process isn't using mailmerge, so why are you using mergefields? What you're doing is a total misuse of them. If you're not doing a mailmerge, you should be using bookmarks, or maybe even content controls. As it is, though, automating a proper mailmerge might significantly simplify things. Nevertheless, whether you use mailmerge or some other form of automation, you'll need to parse your value data after it appears in the document.
__________________
Cheers,
Paul Edstein
[MS MVP - Word]
Reply With Quote
  #5  
Old Today, 01:08 AM
shahid.majeed shahid.majeed is online now Unable to insert line break or carriage return in mail merge field Windows 10 Unable to insert line break or carriage return in mail merge field Office 2013
Novice
Unable to insert line break or carriage return in mail merge field
 
Join Date: Sep 2019
Posts: 3
shahid.majeed is on a distinguished road
Default

Yes you are right there is no need to use mailmerge field in my example code.
My requirement is i have template document with some placeholder where i can put the dynamic data. For example i want to add User name and address.

So i need a place holder to know where is user name in the document that i should replace with real user namer.

There are multiple ways to do such use some sort of tokens and just replace such as ###USERNAME### or as you suggest bookmarks etc.

Unfortunatly first example i found at internet regarding my requirment is with mailMarge so i used that.
Reply With Quote
Reply

Tags
line breaking, mergefield

Thread Tools
Display Modes


Similar Threads
Thread Thread Starter Forum Replies Last Post
Unable to insert line break or carriage return in mail merge field Find / Replace hard Carriage Return with Line break. GreenBoy Word 2 03-11-2018 02:32 AM
Unable to insert line break or carriage return in mail merge field Remove Carriage Returns in Address Block Merge field alan100 Mail Merge 5 12-12-2017 08:32 PM
Adding a carriage return at end of each line, and then a blank space, after text entry complete CEMurphy4 Word VBA 1 12-02-2015 11:53 PM
How to automatically insert a line after a Column Break YooperNC Word 3 01-29-2015 07:16 AM
Unable to insert line break or carriage return in mail merge field Mail merge line break camlad Mail Merge 3 06-29-2011 05:01 PM


All times are GMT -7. The time now is 01:31 AM.


Powered by vBulletin® Version 3.8.11
Copyright ©2000 - 2019, vBulletin Solutions Inc.
Search Engine Optimisation provided by DragonByte SEO (Lite) - vBulletin Mods & Addons Copyright © 2019 DragonByte Technologies Ltd.
MSOfficeForums.com is not affiliated with Microsoft