DataTplTopProduct.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 sample is similar to DataTplProductList but it sorts the product
  18. // list by price in the descending order to print 10 most expensive products.
  19. // To limit the list this sample uses the seq/follow formatter as a 'take(N)'
  20. // operator, utilizing also the ability to use multiple data sources.
  21. // The template document is modified to include the sequence/follow formatters.
  22. public class DataTplTopProduct
  23. {
  24. public GcWordDocument CreateDocx()
  25. {
  26. // The number of iterations:
  27. const int N = 10;
  28.  
  29. // Load and modify the template DOCX:
  30. var doc = new GcWordDocument();
  31. doc.Load(Path.Combine("Resources", "WordDocs", "ProductListTemplate.docx"));
  32. var caption0 = "Product List";
  33. var caption1 = $"{N} Most Expensive Products";
  34. var pStart0 = @"{{#ds}}{{ds.ProductID}}";
  35. var pEnd0 = @"{{/ds}}";
  36. var pStart1 = @"{{#take}:seq(t10)}{{#ds}:follow(t10)}{{ds.ProductID}}";
  37. var pEnd1 = @"{{/ds}}{{/take}}";
  38.  
  39. doc.Body.Replace(caption0, caption1);
  40. doc.Body.Replace(pEnd0, pEnd1);
  41. doc.Body.Replace(pStart0, pStart1);
  42.  
  43. // Add a simple array to be used as the sequence data source
  44. // limiting the number of iterations over the "real" data range:
  45. doc.DataTemplate.DataSources.Add("take", new int[N]);
  46.  
  47. using var ds = new DataSet();
  48. // Load the data and build the product list data source:
  49. ds.ReadXml(Path.Combine("Resources", "data", "DsNWind.xml"));
  50.  
  51. DataTable dtProds = ds.Tables["Products"];
  52. DataTable dtSupps = ds.Tables["Suppliers"];
  53.  
  54. var products =
  55. from prod in dtProds.Select()
  56. join supp in dtSupps.Select()
  57. on prod["SupplierID"] equals supp["SupplierID"]
  58. orderby prod["UnitPrice"] descending
  59. select new
  60. {
  61. ProductID = prod["ProductID"],
  62. ProductName = prod["ProductName"],
  63. Supplier = supp["CompanyName"],
  64. QuantityPerUnit = prod["QuantityPerUnit"],
  65. UnitPrice = prod["UnitPrice"]
  66. };
  67.  
  68. // Add the data source to the data template data sources:
  69. doc.DataTemplate.DataSources.Add("ds", products);
  70.  
  71. // The document already has all the necessary bindings,
  72. // so we only need to process the data template:
  73. doc.DataTemplate.Process(CultureInfo.GetCultureInfo("en-US"));
  74.  
  75. // Done:
  76. return doc;
  77. }
  78. }
  79. }
  80.