How to update Merge Field text

Hi,

We have a bunch of documents where we would like to update Merge Fields. We have a simple solution to do this, however, there are some cases where it does not work.

Can you tell me how we can simply amend the text on a field?

Please see the example word documents and a piece of code which works for the first one but does not for the second one.

Fields.zip (22.0 KB)

        var masks = new Tuple<string, string>("\\#,###.00", "\\# ,0.00;,0.00");
        var document = new Document("pathToDocument");
        var fields = document.Range.Fields;
        foreach (Field field in fields)
        {
            var fieldCode = field.GetFieldCode(false);
            var updatedFieldCode = fieldCode.Replace(masks.Item1, masks.Item2);

            var fieldText = field.Start.NextSibling;
            fieldText.Range.Replace(fieldCode, updatedFieldCode, new FindReplaceOptions());

            field.Update();
        }
        document.UpdateFields();

Thanks,
Lukasz

@acturisaspose

Thanks for your inquiry. Please use FieldMergeField.Format.NumericFormat property to get or set a formatting that is applied to a numeric field result. Corresponds to the # switch. The FieldMergeField class implements the MERGEFIELD field.

Please use the following code example to get the desired output.

Document document = new Document(MyDir + "SecondNotWorking.dot");
var masks = new Tuple<string, string>("\\#,###.00", "\\# ,0.00;,0.00");
                
var fields = document.Range.Fields;
foreach (Field field in fields)
{

    if (field.Type == FieldType.FieldMergeField)
    {
        FieldMergeField fmerge = (FieldMergeField)field;
        fmerge.Format.NumericFormat = masks.Item2;
    }

    var fieldCode = field.GetFieldCode(false);
    field.Update();
}
document.UpdateFields();
document.Save(MyDir + "18.10.docx");

Hi Tahir,

Thank you for your response and the code example. I have tried setting this using NumericFormat, however, there is an issue when changing it.

Using your code example my field changes from MERGEFIELD "QTEPOL_AddOnAmountDue" \#,###.00 to MERGEFIELD "QTEPOL_AddOnAmountDue" \#"\\# ,0.00;,0.00". It looks like the NumericFormat does not contain the # switch.

I have also tried to assign " ,0.00;,0.00" to NumericFormat without the switch, however, I end up with additional double quotation mark in the field, i.e. MERGEFIELD "QTEPOL_AddOnAmountDue" \#" ,0.00;,0.00".

Is there any way to remove the quotation mark or maybe change the mask in the fieldCode?

Thanks,
Lukasz

@acturisaspose

Thanks for your inquiry. Please manually create your expected Word document using Microsoft Word and attach it here for our reference. We will investigate how you want your final Word output be generated like. We will then provide you more information on this.

Hi Tahir,

Please use any of the templates attached to my original message. The mergefield I am mentioning in my previous message is located as a first mergefield in “FirstWorking.dot” template.

Thank you,
Lukasz

@acturisaspose

Thanks for your inquiry. Please do not use the \# in the masks variable to get the desired output.

Hi Tahir,

Please refer to one of my previous messages, there is one case I described where I do not use # and I end up with additional question mark in the field.

Can you also tell me why we cannot simply change the field code by

        var fieldCode = field.GetFieldCode(false);
        var updatedFieldCode = fieldCode.Replace(masks.Item1, masks.Item2); *

*this is a part of my code in original message.

Thank you,
Lukasz

@acturisaspose

Thanks for your inquiry. Please note that the content between the field start and separator is the field code. It can be in one Run node or multiple Run nodes.

Your code does not work for “SecondNotWorking.dot” because field codes are in multiple Run nodes and you are replacing text only in first Run node. Please check the attached DOM image. In “FirstWorking.dot”, the field codes are only in one Run node.

Please call Document.JoinRunsWithSameFormatting method after importing the document into Aspose.Words’ DOM. It will join runs nodes with same formatting in all paragraphs of the document. After calling this method, your code will work for “SecondNotWorking.dot”.

var document = new Document(MyDir + "SecondNotWorking.dot");
document.JoinRunsWithSameFormatting();

Hope this answers your query. Please let us know if you have any more queries.

Hi Tahir,

Thank you for your response and the suggestion, it is reasonable, however, I would prefer to use NumberFormat to do the change.

Can you tell me why there is the additional quotation mark after I change the mask there?

Thank you,
Lukasz

@acturisaspose

Thanks for your inquiry. We have tested the scenario using latest version of Aspose.Words for .NET 18.10 and have not found the additional quotation mark. Please use Aspose.Words for .NET 18.10.

If you still face problem, please share the mail merge field for which you are getting additional quotation mark.

Hi Tahir,

I am using 18.11 version of Aspose Words and I have cases where I cannot replace masks in a document. Please see the document I cannot achieve what I need. Masks.zip (14.8 KB)

I tried using numeric format, as in your proposal, but it is null before change.

        var template = @"YourPath\Masks.dotx";
        var masks = new Tuple<string, string>("\\#,0.00", "\\# ,0.00;,0.00");

        var document = new Document(template);
        var fields = document.Range.Fields.Where(f=>f.Type==FieldType.FieldMergeField);
        foreach (Field field in fields)
        {
            field.Format.NumericFormat = masks.Item2;

            field.Update();
        }
        document.UpdateFields();

        document.Save(@"YourPath\MasksConverted.dotx");

I have also tried running the below code, but it does not work for all of the masks in the document.

        var template = @"YourPath\Masks.dotx";
        var masks = new Tuple<string, string>("\\#,0.00", "\\# ,0.00;,0.00");

        var document = new Document(template);
        document.JoinRunsWithSameFormatting();
        var fields = document.Range.Fields.Where(f=>f.Type==FieldType.FieldMergeField);
        
        foreach (Field field in fields)
        {
            var fieldCode = field.GetFieldCode(false);
            var updatedFieldCode = fieldCode.Replace(masks.Item1, masks.Item2);
            fieldCode = updatedFieldCode;

            //therefore we do this, however, this does not work for all of the other cases
            var fieldText = field.Start.NextSibling;
            fieldText.Range.Replace(fieldCode, updatedFieldCode, new FindReplaceOptions());

            //so we do this
            if (!fieldText.Range.Text.Contains(masks.Item1))
            {
                var children = field.Start.ParentNode.GetChildNodes(NodeType.Run, true);

                foreach (Run run in children)
                {
                    if (run.Text.Contains(masks.Item1) || masks.Item1.Contains(run.Text))
                        run.Text = run.Text.Replace(masks.Item1, masks.Item2);
                }
            }
        }
        document.UpdateFields();

        document.Save(@"YourPath\MasksConverted.dotx");

Do you have any advice?
Could you also tell me why for some cases assigning a new fieldCode to the field works in other it does not?

Thanks,
Lukasz

@acturisaspose

Thanks for your inquiry.

Your document does not has the filed with numeric formatting. This is the reason of null value.

Could you please share some more detail about your issue that you are facing?

Moreover, please manually create your expected Word document using Microsoft Word and attach it here for our reference. We will investigate how you want your final Word output be generated like. We will then provide you more information on this along with code.

Hi Tahir,

Thank you for your response.

What I need to achieve is to change masks in the attached Masks.dotx document from “#,0.00” to “# ,0.00;,0.00”.

Please see the expected document with 4 of “#,0.00” masks changed to “# ,0.00;,0.00” .

Expected document -> Expected.zip (14.8 KB)

Thank you,
Lukasz

@acturisaspose

Thanks for sharing the detail. The numeric formatting is applied to formula fields in your document. Please use the following code example to get the desired output.

var template = MyDir + @"Masks.dotx";
var masks = new Tuple<string, string>("\\#,0.00", " ,0.00;,0.00");

var document = new Document(template);
var fields = document.Range.Fields.Where(f => f.Type == FieldType.FieldFormula);
foreach (Field field in fields)
{
    if (field.Format.NumericFormat != null)
    {
        field.Format.NumericFormat = masks.Item2;
        field.Update();
    }
}

document.UpdateFields();
document.Save(MyDir + @"18.12.docx");

Hi Tahir,

Thank you for your response. I have used your code example, however, when numeric format is changed like that the it is rendered with double quotation marks around it.

Can you advise?

Thanks,
Lukasz

@acturisaspose

Thanks for your inquiry. We have not found the shared issue. Have you tried the latest version of Aspose.Words for .NET 18.12? Please try it and let us know if you still face face problem.

Hi Tahir,

Yes, I am using 18.12. Please see the result document Result.zip (23.5 KB)
that I get after running the code below. It has additional double quotation marks around the mask, just after '# '.

        var template = @"YourDir\Masks.dotx";
        var masks = new Tuple<string, string>("\\#,0.00", " ,0.00;,0.00");

        var document = new Document(template);
        document.JoinRunsWithSameFormatting();
        var fields = document.Range.Fields.Where(f => f.Type == FieldType.FieldFormula);
        foreach (Field field in fields)
        {
            if (field.Format.NumericFormat != null)
            {
                field.Format.NumericFormat = masks.Item2;
                field.Update();
            }
        }
        document.UpdateFields();

        document.Save(@"YourDir\Result.dotx");

Thanks,
Lukasz

@acturisaspose

Thanks for sharing the detail. We have logged this problem in our issue tracking system as WORDSNET-17899. You will be notified via this forum thread once this issue is resolved.

We apologize for your inconvenience.

Hi Tahir,

Thank you. Would you have any workaround for the time being?

Replacing masks using Numeric Format is one way of doing this, however, I have also used some other ways described before, which do not work for cases when mask is split between multiple Run nodes (as in the attached in this thread Masks.dotx template).

Thanks,
Lukasz

@acturisaspose

Thanks for your inquiry. You can use Range.Replace method as show below to workaround this issue. Hope this helps you.

document.UpdateFields();
document.Range.Replace(@""" ,0.00;,0.00""", " ,0.00;,0.00", new FindReplaceOptions());
document.Save(MyDir + "Result.dotx");