AlternatingRows.cs
C# VB
//// This code is part of Document Solutions for Word demos.// Copyright (c) MESCIUS inc. All rights reserved.//using System.Drawing;using System.Collections.Generic;using GrapeCity.Documents.Word;
namespace DsWordWeb.Demos{ // This sample uses conditional table formatting to build a table // with alternating row backgrounds. public class AlternatingRows { public GcWordDocument CreateDocx() { GcWordDocument doc = new GcWordDocument();
// Random-ish table dimensions: var rand = Util.NewRandom(); var rows = rand.Next(10, 100); var cols = rand.Next(4, 6);
doc.Body.Paragraphs.Add( $"A {cols} columns by {rows} rows table, with conditional styles applied to alternating rows:");
// Add an empty table: var t = doc.Body.Tables.Add(0, 0);
// Add some rows and cells to it: var cells = new List<string>(cols); for (int col = 0; col < cols; ++col) cells.Add(string.Empty); for (int row = 0; row < rows; ++row) { for (int col = 0; col < cols; ++col) cells[col] = $"Row {row + 1}, col {col + 1}"; t.Rows.Add(cells.ToArray()); }
// Create a table style on which we will define conditional formatting: var ts1 = doc.Styles.Add("Table Style 1", StyleType.Table); // And assign the style to the table: t.Style = ts1;
// Set up simple borders: foreach (var border in ts1.Table.Borders) { border.LineStyle = LineStyle.Single; border.LineWidth = 0.5f; border.Color.RGB = Color.DarkGray; } // Add some padding: ts1.Table.Padding.All = 2;
// To use certain table styles, we need to set corresponding flags on the table's style options: t.Format.StyleOptions = TableStyleOptions.RowBands;
// Set up the style to use alternating background colors on odd and even rows: ts1.Table.RowStripe = 1; // Odd rows' style: ts1.Table.Conditionals[TableStyleOverride.Band1Horizontal].Shading.Texture = TexturePattern.Clear; ts1.Table.Conditionals[TableStyleOverride.Band1Horizontal].Shading.BackgroundPatternColor.RGB = Color.FromArgb(0xe6, 0xff, 0xe6); // Even rows' style: ts1.Table.Conditionals[TableStyleOverride.Band2Horizontal].Shading.Texture = TexturePattern.Clear; ts1.Table.Conditionals[TableStyleOverride.Band2Horizontal].Shading.BackgroundPatternColor.RGB = Color.FromArgb(0xff, 0xff, 0xe6);
// Done: return doc; } }}