arame3333
arame3333

Reputation: 10193

Word interop; replacing some text with a line break

I have a word document as a template and I want to replace a placeholder; #Address with a number of lines of text. It works except that the Environment.NewLine gets ignored. So how do I put in a line break for each new line? I should point out that in the code, addressLines is a string made up of each line in the collection seperated by a comma and the standard new line constant.

public static void PrintAddress(string companyName, List<string> lines, string outputFolder)
{
    // TODO put in linebreak for each line of the address
    lines.Insert(0, companyName);
    var lineEnd = "," + Environment.NewLine;
    var addressLines = string.Join(lineEnd, lines.ToArray());
    var application = new Application();
    var path = Path.Combine(HttpContext.Current.Server.MapPath(AppSettings.UploadFolder), SessionObjectsSCD.UploadedFile.FileName);
    var document = application.Documents.Open(path);
    WordDocumentClass.FindAndReplace(document, "#ADDRESS", addressLines);
    object filename = string.Format("{0}/{1}.docx", outputFolder, companyName);
    document.SaveAs(ref filename);

    // TODO print document

    application.Quit();
}

public static void FindAndReplace(Document document, string placeHolder, string newText)
{
    object missingObject = null;
    object item = WdGoToItem.wdGoToPage;
    object whichItem = WdGoToDirection.wdGoToFirst;
    object replaceAll = WdReplace.wdReplaceAll;
    object forward = true;
    object matchAllWord = true;
    object matchCase = false;
    object originalText = placeHolder;
    object replaceText = newText;

    document.GoTo(ref item, ref whichItem, ref missingObject, ref missingObject);
    foreach (Range rng in document.StoryRanges)
    {
        rng.Find.Execute(
            ref originalText,
            ref matchCase,
            ref matchAllWord,
            ref missingObject,
            ref missingObject,
            ref missingObject,
            ref forward,
            ref missingObject,
            ref missingObject,
            ref replaceText,
            ref replaceAll,
            ref missingObject,
            ref missingObject,
            ref missingObject,
            ref missingObject);
    }
}

Upvotes: 2

Views: 4819

Answers (2)

arame3333
arame3333

Reputation: 10193

I found that this is the answer; var lineEnd = ",\x0B";

Next time I will try Open XML Toolkit as mentioned in the other answer.

Upvotes: 3

Remy
Remy

Reputation: 12703

I would recommend against Office Interop. A better way is to use the Open XML Toolkit and then approach it like MailMerge. There are multiple articles out there, but this one is a start:

http://blogs.msdn.com/b/ericwhite/archive/2009/02/05/move-insert-delete-paragraphs-in-word-processing-documents-using-the-open-xml-sdk.aspx

Upvotes: 1

Related Questions