DataTplProductIf.cs
  1. //
  2. // This code is part of Document Solutions for Word demos.
  3. // Copyright (c) MESCIUS inc. All rights reserved.
  4. //
  5. using System;
  6. using System.IO;
  7. using System.Drawing;
  8. using System.Collections.Generic;
  9. using System.Text;
  10. using System.Data;
  11. using System.Linq;
  12. using System.Globalization;
  13. using GrapeCity.Documents.Word;
  14.  
  15. namespace DsWordWeb.Demos
  16. {
  17. // This example is similar to DataTplProductList, but additionally
  18. // the code uses report templates' conditional construct '{{if...}}..{{else}}..{{endif}}'
  19. // to filter data so that only products with price greater than $50 are included.
  20. // Note that the filtered data is rendered as a table, each record in a separate table row.
  21. // If the first column of a table starts with '{{if...}}' and ends with '{{endif}}',
  22. // empty rows added as the result of template expansion will be removed.
  23. public class DataTplProductIf
  24. {
  25. public GcWordDocument CreateDocx()
  26. {
  27. // Load and modify the template DOCX:
  28. var doc = new GcWordDocument();
  29. doc.Load(Path.Combine("Resources", "WordDocs", "ProductListTemplate.docx"));
  30. var caption0 = "Product List";
  31. var caption1 = $"Products that cost more than $50";
  32. var pStart0 = @"{{#ds}}{{ds.ProductID}}";
  33. var pEnd0 = @"{{/ds}}";
  34. // NOTE: for empty rows to be automatically removed, the first cell in the template row
  35. // must start with {{if ...}}, and the last cell must end with matching {{endif}}:
  36. var pStart1 = @"{{if ds.UnitPrice > 50}}{{ds.ProductID}}";
  37. var pEnd1 = @"{{endif}}";
  38.  
  39. doc.Body.Replace(caption0, caption1);
  40. doc.Body.Replace(pEnd0, pEnd1);
  41. doc.Body.Replace(pStart0, pStart1);
  42.  
  43. using var ds = new DataSet();
  44. // Load data and build the product list data source:
  45. ds.ReadXml(Path.Combine("Resources", "data", "DsNWind.xml"));
  46.  
  47. DataTable dtProds = ds.Tables["Products"];
  48. DataTable dtSupps = ds.Tables["Suppliers"];
  49.  
  50. var products =
  51. from prod in dtProds.Select()
  52. join supp in dtSupps.Select()
  53. on prod["SupplierID"] equals supp["SupplierID"]
  54. orderby prod["UnitPrice"] descending
  55. select new
  56. {
  57. ProductID = prod["ProductID"],
  58. ProductName = prod["ProductName"],
  59. Supplier = supp["CompanyName"],
  60. QuantityPerUnit = prod["QuantityPerUnit"],
  61. UnitPrice = prod["UnitPrice"]
  62. };
  63.  
  64. // Add the data source to the data template data sources:
  65. doc.DataTemplate.DataSources.Add("ds", products);
  66.  
  67. // Process the template:
  68. doc.DataTemplate.Process(CultureInfo.GetCultureInfo("en-US"));
  69. // Done:
  70. return doc;
  71. }
  72. }
  73. }
  74.