Skip to main content Skip to footer

Conditionally Show/Hide Data in C# .NET .docx Word Report Templates

Although organizations of all types use complex reporting, and many utilize Microsoft Word documents as the file of choice, it is unnecessary to recreate complex reports from scratch each time. Instead, it's better to use a template approach, many of which are standardized in various industries and organizations.

Once a templated approach in a Word .docx file has been established, it is easy with GrapeCity Documents for Word (GcWord) API to bind data to the word .docx template, creating dynamic, complex, and flexible Word .docx format reports using GcWord Templates feature. The API saves the Word reports as .docx files, PDF files, or images. Developers can create a Word template using the mustache syntax to define the database fields, variables, bullets, lists, multi-level lists, and tables. This formatting makes it easy to replace the templated fields (those notated in mustache format).

A data source is added by using the GcWordDocument.DataTemplate.DataSources collection and binding the data with the template using the GcWordDocument.DataTemplate.Process() method. This template API will detect the fields, match them with the appropriate data in the database and replace them with the actual data. There is also an option for batch processing through the DataTemplate.BatchProcess() method to generate a data-bound copy of the document for each iterated data object without changing the current document.

The following is a snapshot of a Closing Disclosure Word Template and the resulting Word Report upon processing the template:

C# .docx

Take total control of Word documents with the fastest Word API available for .NET 6! Download GrapeCity Documents for Word Today!

Generate the following reports:

  • Legal
  • Employee Contracts
  • House Lease Agreements
  • Invoices
  • Flight ticket
  • Itinerary
  • Price catalogs
  • And more

Have a look at this tutorial to see how to bind Word Report Templates with the database using GcWord Report Templates feature.

Conditionally show/hide data in Word Report Templates .docx using C# .NET

Often in data-bound Word reports, especially Legal or Consulting Agreement Contracts, some clauses need to be hidden depending on who the viewer of the document is. Or certain sections need to be shown if only certain conditions are true upon processing the template.

GcWord Report Templates supports ‘if/else/endif’ statements to define conditions to simultaneously show/hide whole block or multiple blocks. The condition defined is a set of template value operands combined with arithmetic or logic operations.

Consider the following example, which shows or hides retainer information from a Consulting Agreement document with a single if/endif condition (shows retainer information if payRetainer=1). This is an alternative and easier method than hiding specific blocks using hbi statements. Also, hbi will only hide a specific line, but if/else/endif statements can show/hide multiple lines.

To achieve this, set the if/endif condition in the Word Template file -

{{if (payRetainer)}}
{{retainerAmount}:format(C)}
A retainer of {{retainerAmount}:format(C)} (the "Retainer") is payable by the Client upon execution of this Agreement.
{{endif}}

The Word Template would look like this:

C# .docx

Import this Word Template file in GcWord, bind it with data, process the template, and save it to a .docx file.

var doc = new GcWordDocument();
doc.Load("Consulting_Agreement_Template.docx");
using (var ds = new DataSet())
{
    ds.ReadXml("GcWordTplDataSet.xml");
    doc.DataTemplate.DataSources.Add("ds", ds.Tables[0]);
    doc.DataTemplate.Process();
    doc.Save("ConsultingAgreement.docx");

}

Have a look at the following screenshot. In the data, payRetainer is turned off, so the clause for the retainer amount to be paid is not displayed.

#C .NET Conditional Template

Show products with a price greater than $50

Also, check out the sample where Products only with a Price greater than $50 are shown in the Table. To achieve this, you can also include the if/else/endif statements in the code.

The code below uses report templates' conditional construct '{{if...}}..{{else}}..{{endif}} to filter data so that only products with a price greater than $50 are included. If the first column of a table starts with '{{if...}}' and ends with '{{endif}}', empty rows added as the result of template expansion will be removed.

var caption0 = "Product List";
var caption1 = $"Products that cost more than $50";
var pStart0 = @"{{#ds}}{{ds.ProductID}}";
var pEnd0 = @"{{/ds}}";
// NOTE: for empty rows to be automatically removed, the first cell in the template row
// must start with {{if ...}}, and the last cell must end with matching {{endif}}:
var pStart1 = @"{{if ds.UnitPrice > 50}}{{ds.ProductID}}";
var pEnd1 = @"{{endif}}";
 
doc.Body.Replace(caption0, caption1);
doc.Body.Replace(pEnd0, pEnd1);
doc.Body.Replace(pStart0, pStart1);

Load the data set and bind the Word template with data. Process the template and save the Word file.

using (var ds = new DataSet())
{
                // Load data and build the product list data source:
                ds.ReadXml(Path.Combine("Resources", "data", "GcNWind.xml"));
 
                DataTable dtProds = ds.Tables["Products"];
                DataTable dtSupps = ds.Tables["Suppliers"];
 
                var products =
                    from prod in dtProds.Select()
                    join supp in dtSupps.Select()
                    on prod["SupplierID"] equals supp["SupplierID"]
                    orderby prod["UnitPrice"] descending
                    select new
                    {
                        ProductID = prod["ProductID"],
                        ProductName = prod["ProductName"],
                        Supplier = supp["CompanyName"],
                        QuantityPerUnit = prod["QuantityPerUnit"],
                        UnitPrice = prod["UnitPrice"]
                    };
 
                // Add the data source to the data template data sources:
                doc.DataTemplate.DataSources.Add("ds", products);
 
                // Process the template:
                doc.DataTemplate.Process();
}
doc.Save("ProductList.docx");

Here is what the Word report looks like:

C# .docx

For a complete sample, visit this link.

Visit the following links to learn more about features supported with GcWord Templates.

We hope you like this feature. Share your use cases where you would like to use if/else/endif statements in your Word .docx Templates. Leave your comments below. 

Take total control of Word documents with the fastest Word API available for .NET 6! Download GrapeCity Documents for Word Today!

 

comments powered by Disqus