Generate a DOCX with a nested list that is restarted for each top list entry

DOCX PDF TIFF SVG JPG PNG C# VB
DataTplRestartList.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.Linq;
  10. using System.Globalization;
  11. using GrapeCity.Documents.Word;
  12.  
  13. namespace DsWordWeb.Demos
  14. {
  15. // This sample demonstrates the use of the restart list formatter
  16. // to print the list of oceans and each ocean's list of seas,
  17. // restarting the inner seas list for each ocean.
  18. // This sample is similar to DataTplNestedList but uses a JSON
  19. // data source, and restarts the nested list for each ocean.
  20. public class DataTplRestartList
  21. {
  22. public GcWordDocument CreateDocx()
  23. {
  24. var doc = new GcWordDocument();
  25.  
  26. // Add JSON data source to the data template data sources:
  27. using (var oceans = File.OpenRead(Path.Combine("Resources", "data", "oceans.json")))
  28. doc.DataTemplate.DataSources.Add("ds", oceans);
  29.  
  30. // Our document consists of a top list with ocean names,
  31. // and a nested list with each ocean's sea names.
  32. // The ':restart()' formatter associated with a range restarts
  33. // the nested lists on each iteration over the range,
  34. // but does not restart the outer list - which is what we
  35. // want in this and most other cases (to restart the topmost list too,
  36. // use the optional 'all' parameter ':restart(all)'):
  37. var pTop = doc.Body.Paragraphs.Add("{{#ds}:restart()}{{ds.name}} Ocean:", doc.Styles[BuiltInStyleId.ListNumber]);
  38. var pNested = doc.Body.Paragraphs.Add("{{#ds.seas}}{{ds.seas.name}}{{/ds.seas}}{{/ds}}", doc.Styles[BuiltInStyleId.ListNumber2]);
  39.  
  40. // Add list templates and set up list formatting:
  41. var topListTemplate = doc.ListTemplates.Add(BuiltInListTemplateId.NumberDefault, "topListTemplate");
  42. var nestedListTemplate = doc.ListTemplates.Add(BuiltInListTemplateId.NumberDefault, "nestedListTemplate");
  43. pTop.ListFormat.Template = topListTemplate;
  44. pNested.ListFormat.Template = nestedListTemplate;
  45. pNested.ListFormat.LevelNumber = 1;
  46.  
  47. // This call expands all data templates in the document,
  48. // replacing template tags with data (iterating over all data items):
  49. doc.DataTemplate.Process(CultureInfo.GetCultureInfo("en-US"));
  50.  
  51. // Done:
  52. return doc;
  53. }
  54. }
  55. }
  56.