Apply Table Styles

This example demonstrates how to apply table styles.

When in need of data display, a table view is often used since table view presents data in a scrollable list of multiple rows that may be divided into sections. Applying styles to it makes it more highligh and also helps describe data and show comparision.

Clicking on the Generate button to create a word file for the selected Word format. In the file you will notice that rows have alternating color which makes them look more aesthetically user friendly

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Text;

using OfficeComponent.Word;
using System.Data.SqlServerCe;
using System.Data;

namespace OfficeComponent.Samples
{
    class ApplyTableStylesExample : WordExampleBase
    {
        public ApplyTableStylesExample(string commonDataPath, string outputDir)
            : base(commonDataPath, outputDir)
        {

        }

        public ApplyTableStylesExample(string commonDataPath, string outputDir, string xmlFile) : base(commonDataPath, outputDir, xmlFile)
        {

        }

        public override string Execute()
        {
            WordDocument document = new WordDocument(CommonDataPath + "\\TableTemplate.doc");

#if USEDB
            AppDomain.CurrentDomain.SetData("SQLServerCompactEditionUnderWebHosting", true);
            string connectionstring = CommonDataPath + "\\NorthwindIO.sdf";
            string sqlMobileConnString1 = @"Data Source = " + connectionstring;

            DataTable table = new DataTable("Employees");
            SqlCeConnection conn = new SqlCeConnection(sqlMobileConnString1);
            conn.Open();
            SqlCeDataAdapter adapter = new SqlCeDataAdapter("Select * from Employees", conn);
            adapter.Fill(table);
            adapter.Dispose();
            conn.Close();
#else
            DataTable table = GetDataTable();
#endif
            document.MailMerge.ExecuteGroup(table);

            #region Built-in table styles
            //Get table to apply style.
            Table docTable = document.LastSection.Tables[0];

            //Apply built-in table style to the table.
            docTable.ApplyStyle(TableStyleIdentifier.LightShadingAccent5);
            #endregion

            string fileName = Path.Combine(OutputDir, this.GetType().Name + "_" + Guid.NewGuid().ToString() + GetExtension(SaveAsFormat));
            // Save the document.
            document.Save(fileName, SaveAsFormat);

            // Close the document.
            document.Close();

            // Ask user whether he/she wants to open the generated file.

            return fileName;
        }

        /// 
        /// Gets fictitious order by id.
        /// 
        private DataTable GetDataTable()
        {
            DataTable dt = new DataTable("Employees");
            dt.Columns.Add("EmployeeID", typeof(int));
            dt.Columns.Add("LastName", typeof(string));
            dt.Columns.Add("FirstName", typeof(string));
            dt.Columns.Add("Title", typeof(string));
            dt.Columns.Add("TitleOfCourtersy", typeof(string));
            dt.Columns.Add("BirthDate", typeof(DateTime));
            dt.Columns.Add("HireDate", typeof(DateTime));
            
            dt.Columns.Add("Address", typeof(string));
            dt.Columns.Add("City", typeof(string));
            dt.Columns.Add("Region", typeof(string));
            dt.Columns.Add("PostalCode", typeof(string));
            dt.Columns.Add("Country", typeof(string));
            dt.Columns.Add("HomePhone", typeof(string));
            dt.Columns.Add("Extension", typeof(string));
            dt.Columns.Add("Notes", typeof(string));
            dt.Columns.Add("ReportsTo", typeof(string));

            for (int i = 0; i < 50; i++)
            {
                string name = GetRandomName();
                int n = name.IndexOf(' ');
                dt.Rows.Add(1000 + i, 
                    name.Substring(n + 1), 
                    name.Substring(0, n), 
                    "Mr.",
                    "Mr.", 
                    new DateTime(1970, 10, 10),
                    new DateTime(2010, 10, 10),
                    GetRandomAddress(), GetRandomCity(), GetRandomPostalCode(), GetRandomCountry(),
                    "123-456-7890",
                    "333",
                    null,
                    null
                    );
            }

            return dt;
        }

        Random random = new Random(Environment.TickCount);

        private string GetRandomAddress()
        {
            string[] list = new string[]
                                 {
                                     "Avda. de la Constitucion 2222",
                                     "Mataderos 2312",
                                     "120 Hanover Sq.",
                                     "Berguvsvagen 8",
                                     "Forsterstr. 57",
                                     "24, place Klober",
                                     "C/ Araquil, 67",
                                     "12, rue des Bouchers",
                                     "23 Tsawassen Blvd.",
                                     "Fauntleroy Circus",
                                 };

            return list[random.Next(list.Length)];
        }

        private string GetRandomName()
        {
            string[] list = new string[]
                                 {
                                     "Maria Anders",
                                     "Ana Trujillo",
                                     "Antonio Moreno",
                                     "Thomas Hardy",
                                     "Christina Berglund",
                                     "Hanna Moos",
                                     "Frederique Citeaux",
                                     "Martin Sommer",
                                     "Laurence Lebihan",
                                     "Elizabeth Lincoln",
                                     "Victoria Ashworth",
                                     "Francisco Chang",
                                     "Yang Wang",
                                 };

            return list[random.Next(list.Length)];
        }

        private string GetRandomCompanyName()
        {
            string[] list = new string[]
                                 {
                                     "Alfreds Futterkiste",
                                     "Around the Horn",
                                     "Berglunds snabbkop",
                                     "Blauer See Delikatessen",
                                     "Bon app'",
                                     "Bottom-Dollar Markets",
                                     "B's Beverages",
                                     "Consolidated Holdings",
                                     "Ernst Handel",
                                     "Folies gourmandes",
                                     "Galeria del gastronomo",
                                     "Hanari Carnes",
                                     "Island Trading",
                                 };

            return list[random.Next(list.Length)];
        }

        private string GetRandomCity()
        {
            string[] list = new string[]
                                 {
                                     "Cork",
                                     "Cowes",
                                     "Versailles",
                                     "Vancouver",
                                     "Walla Walla",
                                     "Frankfurt a.M.",
                                     "San Francisco",
                                     "Barquisimeto",
                                     "Portland",
                                     "Bergamo",
                                     "Bruxelles",
                                     "Montreal",
                                     "Leipzig",
                                     "London",
                                 };

            return list[random.Next(list.Length)];
        }

        private string GetRandomCountry()
        {
            string[] list = new string[]
                                 {
                                     "Germany",
                                     "Venezuela",
                                     "USA",
                                     "Canada",
                                     "Belgium",
                                     "Italy",
                                     "Argentina",
                                     "UK",
                                     "France",
                                     "Mexico",
                                     "Austria",
                                     "Portugal",
                                     "Brazil",
                                     "Switzerland",
                                 };

            return list[random.Next(list.Length)];
        }

        private string GetRandomPostalCode()
        {
            string[] list = new string[]
                                 {
                                     "PO31 7PJ",
                                     "14776",
                                     "78000",
                                     "V3F 2K1",
                                     "99362",
                                     "94117",
                                     "3508",
                                     "24100",
                                     "B-1180",
                                     "SW7 1RZ",
                                     "99508",
                                     "50739",
                                     "05033",
                                     "02389-673",
                                 };

            return list[random.Next(list.Length)];
        }
    }
}
Imports System.Drawing.Imaging
Imports System.IO
Imports System.Text

Imports OfficeComponent.Word
Imports System.Data.SqlServerCe

Namespace OfficeComponent.Samples
	Friend Class ApplyTableStylesExample
		Inherits WordExampleBase
		Public Sub New(ByVal commonDataPath As String, ByVal outputDir As String)
			MyBase.New(commonDataPath, outputDir)

		End Sub

		Public Sub New(ByVal commonDataPath As String, ByVal outputDir As String, ByVal xmlFile As String)
			MyBase.New(commonDataPath, outputDir, xmlFile)

		End Sub

		Public Overrides Function Execute() As String
			Dim document As New WordDocument(CommonDataPath & "\TableTemplate.doc")

#If USEDB Then
			AppDomain.CurrentDomain.SetData("SQLServerCompactEditionUnderWebHosting", True)
			Dim connectionstring As String = CommonDataPath & "\NorthwindIO.sdf"
			Dim sqlMobileConnString1 As String = "Data Source = " & connectionstring

			Dim table As New DataTable("Employees")
			Dim conn As New SqlCeConnection(sqlMobileConnString1)
			conn.Open()
			Dim adapter As New SqlCeDataAdapter("Select * from Employees", conn)
			adapter.Fill(table)
			adapter.Dispose()
			conn.Close()
#Else
			Dim table As DataTable = GetDataTable()
#End If
			document.MailMerge.ExecuteGroup(table)

'			#Region "Built-in table styles"
			'Get table to apply style.
			Dim docTable As Table = document.LastSection.Tables(0)

			'Apply built-in table style to the table.
			docTable.ApplyStyle(TableStyleIdentifier.LightShadingAccent5)
'			#End Region

			Dim fileName As String = Path.Combine(OutputDir, Me.GetType().Name & "_" & Guid.NewGuid().ToString() & GetExtension(SaveAsFormat))
			' Save the document.
			document.Save(fileName, SaveAsFormat)

			' Close the document.
			document.Close()

			' Ask user whether he/she wants to open the generated file.

			Return fileName
		End Function

		''' 
		''' Gets fictitious order by id.
		''' 
		Private Function GetDataTable() As DataTable
			Dim dt As New DataTable("Employees")
			dt.Columns.Add("EmployeeID", GetType(Integer))
			dt.Columns.Add("LastName", GetType(String))
			dt.Columns.Add("FirstName", GetType(String))
			dt.Columns.Add("Title", GetType(String))
			dt.Columns.Add("TitleOfCourtersy", GetType(String))
			dt.Columns.Add("BirthDate", GetType(Date))
			dt.Columns.Add("HireDate", GetType(Date))

			dt.Columns.Add("Address", GetType(String))
			dt.Columns.Add("City", GetType(String))
			dt.Columns.Add("Region", GetType(String))
			dt.Columns.Add("PostalCode", GetType(String))
			dt.Columns.Add("Country", GetType(String))
			dt.Columns.Add("HomePhone", GetType(String))
			dt.Columns.Add("Extension", GetType(String))
			dt.Columns.Add("Notes", GetType(String))
			dt.Columns.Add("ReportsTo", GetType(String))

			For i As Integer = 0 To 49
				Dim name As String = GetRandomName()
				Dim n As Integer = name.IndexOf(" "c)
				dt.Rows.Add(1000 + i, name.Substring(n + 1), name.Substring(0, n), "Mr.", "Mr.", New Date(1970, 10, 10), New Date(2010, 10, 10), GetRandomAddress(), GetRandomCity(), GetRandomPostalCode(), GetRandomCountry(), "123-456-7890", "333", Nothing, Nothing)
			Next i

			Return dt
		End Function

		Private random As New Random(Environment.TickCount)

		Private Function GetRandomAddress() As String
			Dim list() As String = { "Avda. de la Constitucion 2222", "Mataderos 2312", "120 Hanover Sq.", "Berguvsvagen 8", "Forsterstr. 57", "24, place Klober", "C/ Araquil, 67", "12, rue des Bouchers", "23 Tsawassen Blvd.", "Fauntleroy Circus" }

			Return list(random.Next(list.Length))
		End Function

		Private Function GetRandomName() As String
			Dim list() As String = { "Maria Anders", "Ana Trujillo", "Antonio Moreno", "Thomas Hardy", "Christina Berglund", "Hanna Moos", "Frederique Citeaux", "Martin Sommer", "Laurence Lebihan", "Elizabeth Lincoln", "Victoria Ashworth", "Francisco Chang", "Yang Wang" }

			Return list(random.Next(list.Length))
		End Function

		Private Function GetRandomCompanyName() As String
			Dim list() As String = { "Alfreds Futterkiste", "Around the Horn", "Berglunds snabbkop", "Blauer See Delikatessen", "Bon app'", "Bottom-Dollar Markets", "B's Beverages", "Consolidated Holdings", "Ernst Handel", "Folies gourmandes", "Galeria del gastronomo", "Hanari Carnes", "Island Trading" }

			Return list(random.Next(list.Length))
		End Function

		Private Function GetRandomCity() As String
			Dim list() As String = { "Cork", "Cowes", "Versailles", "Vancouver", "Walla Walla", "Frankfurt a.M.", "San Francisco", "Barquisimeto", "Portland", "Bergamo", "Bruxelles", "Montreal", "Leipzig", "London" }

			Return list(random.Next(list.Length))
		End Function

		Private Function GetRandomCountry() As String
			Dim list() As String = { "Germany", "Venezuela", "USA", "Canada", "Belgium", "Italy", "Argentina", "UK", "France", "Mexico", "Austria", "Portugal", "Brazil", "Switzerland" }

			Return list(random.Next(list.Length))
		End Function

		Private Function GetRandomPostalCode() As String
			Dim list() As String = { "PO31 7PJ", "14776", "78000", "V3F 2K1", "99362", "94117", "3508", "24100", "B-1180", "SW7 1RZ", "99508", "50739", "05033", "02389-673" }

			Return list(random.Next(list.Length))
		End Function
	End Class
End Namespace