AlternatingRows.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 GrapeCity.Documents.Word;
  11.  
  12. namespace DsWordWeb.Demos
  13. {
  14. // This sample uses conditional table formatting to build a table
  15. // with alternating row backgrounds.
  16. public class AlternatingRows
  17. {
  18. public GcWordDocument CreateDocx()
  19. {
  20. GcWordDocument doc = new GcWordDocument();
  21.  
  22. // Random-ish table dimensions:
  23. var rand = Util.NewRandom();
  24. var rows = rand.Next(10, 100);
  25. var cols = rand.Next(4, 6);
  26.  
  27. doc.Body.Paragraphs.Add(
  28. $"A {cols} columns by {rows} rows table, with conditional styles applied to alternating rows:");
  29.  
  30. // Add an empty table:
  31. var t = doc.Body.Tables.Add(0, 0);
  32.  
  33. // Add some rows and cells to it:
  34. var cells = new List<string>(cols);
  35. for (int col = 0; col < cols; ++col)
  36. cells.Add(string.Empty);
  37. for (int row = 0; row < rows; ++row)
  38. {
  39. for (int col = 0; col < cols; ++col)
  40. cells[col] = $"Row {row + 1}, col {col + 1}";
  41. t.Rows.Add(cells.ToArray());
  42. }
  43.  
  44. // Create a table style on which we will define conditional formatting:
  45. var ts1 = doc.Styles.Add("Table Style 1", StyleType.Table);
  46. // And assign the style to the table:
  47. t.Style = ts1;
  48.  
  49. // Set up simple borders:
  50. foreach (var border in ts1.Table.Borders)
  51. {
  52. border.LineStyle = LineStyle.Single;
  53. border.LineWidth = 0.5f;
  54. border.Color.RGB = Color.DarkGray;
  55. }
  56. // Add some padding:
  57. ts1.Table.Padding.All = 2;
  58.  
  59. // To use certain table styles, we need to set corresponding flags on the table's style options:
  60. t.Format.StyleOptions = TableStyleOptions.RowBands;
  61.  
  62. // Set up the style to use alternating background colors on odd and even rows:
  63. ts1.Table.RowStripe = 1;
  64. // Odd rows' style:
  65. ts1.Table.Conditionals[TableStyleOverride.Band1Horizontal].Shading.Texture = TexturePattern.Clear;
  66. ts1.Table.Conditionals[TableStyleOverride.Band1Horizontal].Shading.BackgroundPatternColor.RGB = Color.FromArgb(0xe6, 0xff, 0xe6);
  67. // Even rows' style:
  68. ts1.Table.Conditionals[TableStyleOverride.Band2Horizontal].Shading.Texture = TexturePattern.Clear;
  69. ts1.Table.Conditionals[TableStyleOverride.Band2Horizontal].Shading.BackgroundPatternColor.RGB = Color.FromArgb(0xff, 0xff, 0xe6);
  70.  
  71. // Done:
  72. return doc;
  73. }
  74. }
  75. }
  76.