Aspose Word Template Issues

@vlbuch23 Thank you for additional information. As I can see from your code you are using Mail Merge feature to generate the document. Could you please attach your template (MS Word document with merge fields) for testing? Most likely there is a mistake in the template and region for CRSC is defined outside the table.

Sure. Templates.zip (5.7 KB)

@vlbuch23 Thank you for additional information, but you have attached your code again. Template is not the code, it is MS Word document with merge fields.

Ooops. try now. These have actual word documents. CRSC.zip (5.5 MB)

@vlbuch23 Thank you for additional information. The problem is in CRSC\TemplatesFromProd templates. As you can see the region is outside the table:

In your case the region should be inside the table. Also, as you can notice the there is only one field in the region - crsceffdates. In your case there should be two fields for percent value and date. The template should look like this:

Then the pseudocode to fill the region with data will look like this:

// Dummy data
DataTable dt = new DataTable("DateRanges");
dt.Columns.Add("percent");
dt.Columns.Add("date");
dt.Rows.Add("10%", "01.05.2022");
dt.Rows.Add("20%", "02.05.2022");
dt.Rows.Add("30%", "03.05.2022");

// Opent tempate, execute mail merge with regions and save the result.
Document doc = new Document(@"C:\Temp\in.docx");
doc.MailMerge.ExecuteWithRegions(dt);
doc.Save(@"C:\Temp\out.docx");

The result will look like this:

Here is simple input and output documents: in.docx (14.9 KB) out.docx (10.6 KB)

Hello. Yes I saw templates itself have problems. Also SMC Code even if I input 01 its generating as 1. Its stored as number in database I checked. Any ideas on that?

@vlbuch23 You can specify the appropriate number format in the mergefield to have a leading zero in the number. Your mergefield code should look like this { MERGEFIELD test \# "00" }.
For example see the attached documents and the following simple code:

Document doc = new Document(@"C:\Temp\in.docx");
doc.MailMerge.Execute(new string[] { "test" }, new object[] { 1 });
doc.Save(@"C:\Temp\out.docx");

in.docx (12.2 KB) out.docx (9.5 KB)

Ok I did that little slightly different.

if (smccode.Length == 1)
{
    DT.Rows[0]["IsSMC"] = "IS";
    DT.Rows[0]["SMCCde"] = "SMC Code" + " " + "0" + DT.Rows[0]["SMCCode"].ToString() +
        " is combat related and is effective " + DT.Rows[0]["SMCEffectiveDate"].ToString();
}
else
{
    DT.Rows[0]["IsSMC"] = "IS";
    DT.Rows[0]["SMCCde"] = "SMC Code" + " " + DT.Rows[0]["SMCCode"].ToString() +
        " is combat related and is effective " + DT.Rows[0]["SMCEffectiveDate"].ToString();
} 

Last issue I have is I was trying to fix the middlename issue which inserts blank space if middle name does not exist. I have tried multiple things. Can you see below:

if (DT.Rows[0]["PartyMiddleName"].ToString() != "")
{
    DT.Rows[0]["MiddleInitial"] = " " + Util.FormatTextToUpper(DT.Rows[0]["PartyMiddleName"].ToString().Substring(0, 1) + ".");

}
else
{
    DT.Rows[0]["MiddleInitial"] = middle;
}

@vlbuch23 In this case you can use Text After feature of merge field. Field code should look like this: { MERGEFIELD FirstName \f " " }{ MERGEFIELD MidName \f " " }{ MERGEFIELD LastName } As you can see \f " " switch is added to the first two fields, if the field is not empty the text of this switch is added after the field value.
Here is test code and documents:

Document doc = new Document(@"C:\Temp\in.docx");
string[] fieldName = new string[] { "FirstName", "MidName", "LastName" };
string[] fieldValues = new string[] { "Alexey", "", "Noskov" };
doc.MailMerge.Execute(fieldName, fieldValues);
doc.Save(@"C:\Temp\out.docx");

in.docx (12.1 KB) out.docx (9.4 KB)

Got it. and for Combat Tables and Non Combat table its print fields even if its null. We want it to be null if not present.How to achieve that.

@vlbuch23 You can specify mail merge cleanup options to remove unused fields from the document. Please see our documentation for more information.

Ok this is for java what you sent me. Can you send me .net link please. I was trying like below also but still no luck yet.

doc.MailMerge.CleanupOptions = MailMergeCleanupOptions.RemoveEmptyTableRows | MailMergeCleanupOptions.RemoveUnusedFields | MailMergeCleanupOptions.RemoveEmptyParagraphs |MailMergeCleanupOptions.RemoveContainingFields;
Regex regex = new Regex(" ");
FindReplaceOptions options = new FindReplaceOptions();
options.IgnoreFields = true;
// Replace 'e' in document while ignoring deleted text.
options.IgnoreDeleted = true;
// doc.Range.Replace(regex, "", options);
doc.Range.Replace(new Regex(@" <MiddleInitial>,"), string.Empty, options);
doc.Range.Replace(new Regex(@" <Vasrd>,"), string.Empty, options);
doc.Range.Replace(new Regex(@" <crsceffdates>,"), string.Empty, options);
doc.Range.Replace(new Regex(@" <Vasrd1>,"), string.Empty, options);
doc.Range.Replace(new Regex(@" <Vasrd2>,"), string.Empty, options);
doc.Range.Replace(new Regex(@" <Vasrd3>,"), string.Empty, options);
doc.UpdateFields();
doc.Save(this.Response, LetterTemplateEntity.CRSC_LETTER_TEMPLATE_DESC.ToString() + ".docx", Aspose.Words.ContentDisposition.Inline, new OoxmlSaveOptions());

@vlbuch23 I have corrected the link in my previous answer.
You set MailMerge.CleanupOptions correctly, but they should be set before executing mail merge, they are applied upon executing mail merge.
If you simply need to remove merge fields from the document you can use MailMerge.DeleteFields.

Oh k that did the trick. I did it like this and worked.

// Replace 'e' in document while ignoring deleted text.
options.IgnoreDeleted = true;
// doc.Range.Replace(regex, "", options);
doc.Range.Replace(new Regex(@" <MiddleInitial>,"), string.Empty, options);
doc.Range.Replace(new Regex(@" <Vasrd>,"), string.Empty, options);
doc.Range.Replace(new Regex(@" <crsceffdates>,"), string.Empty, options);
doc.Range.Replace(new Regex(@" <Vasrd1>,"), string.Empty, options);
doc.Range.Replace(new Regex(@" <Vasrd2>,"), string.Empty, options);
doc.Range.Replace(new Regex(@" <Vasrd3>,"), string.Empty, options);
doc.MailMerge.CleanupOptions = MailMergeCleanupOptions.RemoveEmptyTableRows | MailMergeCleanupOptions.RemoveUnusedFields | MailMergeCleanupOptions.RemoveEmptyParagraphs | MailMergeCleanupOptions.RemoveContainingFields;
doc.MailMerge.DeleteFields();
doc.UpdateFields();
doc.Save(this.Response, LetterTemplateEntity.CRSC_LETTER_TEMPLATE_DESC.ToString() + ".docx", Aspose.Words.ContentDisposition.Inline, new OoxmlSaveOptions());

A CH61 APPROVAL (TDS) (5).docx (66.6 KB)

My only issue remains is below part now.

Combined % CRSC Effective Date
«TableStart:DateRanges» «crsceffdates»«TableEnd:DateRanges»

So this code I think its printing all percentage and dates to gether. I have attached document as well. I wonder if can extract percentage using some extraction or trim code. If you could share ideas?

Combined % CRSC Effective Date
60% from 01 Oct 2015 for Code(s) 5003 5257 (0%) 5237 (10%) 5271 5003 (10%) 5003 5260 (10%) 7522 (10%) 6260 (10%) 5003 5252 (10%) 8045 (10%)

@vlbuch23 You should modify your template and data source and put percentage and date values into separate fields, like I have described in one on my previous answers.

So based of this function I wanted to use a particular row that is highlighted.

public DataTable RetrieveCombinedCrscPercentages(int caseId)
{
    DecisionController decision = new DecisionController();
    DataSet ds = decision.RetrieveCalculatedCombinedPercentages(caseId);
    DataTable dt = ds.Tables[0].Copy();
    //DataTable dt = new DataTable("RetrieveSlidingPercentage");
    dt.Columns.Add("vasrdDisaPct", typeof(string));
    dt.Columns.Add("crsceffdates", typeof(string));
    dt.Columns.Add("vasrdstartdate", typeof(string));
    dt.Columns.Add("vasrdenddate", typeof(string));
    dt.Columns.Add("VaeffstartDt", typeof(string));
    //dt.Columns.Add("CombDisaPctRnd", typeof(string));

    DataTable pctDT = decision.RetrieveSlidingPercentageList(caseId, true);

    foreach (DataRow dr in dt.Rows)
    {
        DateTime startDate = (dr["StartDate"].ToString() == String.Empty) | dr["StartDate"].ToString().Equals(DateTime.MinValue.ToString()) ?
                        DateTime.MaxValue : DateTime.Parse(String.Format("{0:yyyy/mm/dd}", dr["StartDate"].ToString()));

        DateTime endDate = (dr["EndDate"].ToString() == String.Empty) | dr["EndDate"].ToString().Equals(DateTime.MinValue.ToString()) ?
            DateTime.MaxValue : DateTime.Parse(String.Format("{0:yyyy/mm/dd}", dr["EndDate"].ToString()));

        DataRow[] rows = pctDT.Select("StartDate ='" + startDate.ToString() + "'");

        foreach (DataRow row in rows)
        {
            dr["vasrdDisaPct"] += row["VASRD_1"].ToString() + " " + row["VASRD_2"].ToString() + " " + row["VASRD_3"].ToString() + " (" + row["PERCENTAGE"].ToString() + "%) ";
            dr["vasrdstartdate"] = Util.FormatNotificationDate(dr["StartDate"]);
            dr["vasrdendDate"] = Util.FormatNotificationDate(dr["EndDate"]);

            if (dr["vasrdendDate"].ToString() != "")
            {
                dr["crsceffdates"] = dr["CombDisaPctRnd"].ToString() + "% from " + dr["vasrdstartdate"] + " to " + dr["vasrdenddate"] +
                " for Code(s) " + dr["vasrdDisaPct"];
            }
            else
            {
                dr["crsceffdates"] = **dr["CombDisaPctRnd"].ToString() * *+"% from " + dr["vasrdstartdate"] + " for Code(s) " + dr["vasrdDisaPct"];
            }
        }
    }

    return dt;
}

And in Word Document Template I tried:

Combined % CRSC Effective Date
«TableStart:DateRanges»CombDisaPctRnd«TableEnd:DateRanges»

Why Its not populating it then however. it populates CRSC Effective Dates however. what am I doing wrong.

@vlbuch23 Looks like there is no merge field between TableStart:DateRanges and TableEnd:DateRanges, but I cannot tell for sure without actual document. So please attach your actual template document. I will check it and provide you more information.

hello sure find attached and its in last table if you notice. Also I attached as pdf because your portal does not allow to use
A CRSC APP AND DENIAL (JFM).pdf (135.7 KB)

@vlbuch23 Thank you for additional information. You should put start of region at the beginning of the first cell in row and end of region at the end of the last cell in the row. Please see the attached simple template: in.docx (15.1 KB)

PS: You can zip file and attach it here regardless of its original format.