DataTplProductIf.cs
- //
- // This code is part of Document Solutions for Word demos.
- // Copyright (c) MESCIUS inc. All rights reserved.
- //
- using System;
- using System.IO;
- using System.Drawing;
- using System.Collections.Generic;
- using System.Text;
- using System.Data;
- using System.Linq;
- using System.Globalization;
- using GrapeCity.Documents.Word;
-
- namespace DsWordWeb.Demos
- {
- // This example is similar to DataTplProductList, but additionally
- // the code uses report templates' conditional construct '{{if...}}..{{else}}..{{endif}}'
- // to filter data so that only products with price greater than $50 are included.
- // Note that the filtered data is rendered as a table, each record in a separate table row.
- // 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.
- public class DataTplProductIf
- {
- public GcWordDocument CreateDocx()
- {
- // Load and modify the template DOCX:
- var doc = new GcWordDocument();
- doc.Load(Path.Combine("Resources", "WordDocs", "ProductListTemplate.docx"));
- 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);
-
- using var ds = new DataSet();
- // Load data and build the product list data source:
- ds.ReadXml(Path.Combine("Resources", "data", "DsNWind.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(CultureInfo.GetCultureInfo("en-US"));
- // Done:
- return doc;
- }
- }
- }
-