''
'' This code is part of Document Solutions for Word demos.
'' Copyright (c) MESCIUS inc. All rights reserved.
''
Imports System.Drawing
Imports GrapeCity.Documents.Word
'' This sample creates a simple table,
'' and demonstrates the following table related tasks:
'' - Applying table styles (borders and padding);
'' - Adding rows and cells;
'' - Removing rows;
'' - Fetching text from a specific cell;
'' - Applying character style to a specific cell.
Public Class SimpleTable
Function CreateDocx() As GcWordDocument
Dim doc = New GcWordDocument()
'' Random-ish table dimensions:
Dim rand = Util.NewRandom()
Dim rows = rand.Next(15, 100)
Dim cols = rand.Next(4, 6)
Dim getrow = rand.Next(0, 10)
Dim getcol = rand.Next(0, 4)
Dim badrow = 12 '' index 12 === number 13 :)
Dim section = doc.Body.Sections.First
Dim header = section.GetRange().Paragraphs.Add(
$"A {cols} columns by {rows} rows table (note that the there's no 'row {badrow + 1}'):")
'' Add an empty table:
Dim t = section.GetRange().Tables.Add(0, 0)
'' Add some rows and cells to it:
Dim cells = New List(Of String)(cols)
For col = 1 To cols
cells.Add(String.Empty)
Next
For row = 0 To rows - 1
For col = 0 To cols - 1
cells(col) = $"Row {row + 1}, col {col + 1}"
Next
t.Rows.Add(cells.ToArray())
Next
'' Remove a row:
t.Rows(badrow).Delete()
'' Create a new table style:
Dim ts1 = doc.Styles.Add("Table Style 1", StyleType.Table)
'' Assign the style to the table:
t.Style = ts1
'' We can enumerate all table borders, including inside borders:
For Each border In ts1.Table.Borders
border.LineStyle = LineStyle.Triple
border.LineWidth = 0.5F
border.Color.RGB = Color.Purple
Next
'' Overwrite inside border's line styles:
ts1.Table.Borders.InsideHorizontal.LineStyle = LineStyle.Double
ts1.Table.Borders.InsideVertical.LineStyle = LineStyle.Double
'' Add some cell padding:
ts1.Table.Padding.All = 2
'' Finally, fetch the text from a certain cell and insert it befor the table:
'' Fetching the text from a cell: because we know exactly the structure of our table,
'' we can do this without any checks:
'' - get the cell at index 'getcol' in row 'getrow',
'' - first child fetches the paragraph,
'' - next child fetches the run,
'' - finally, next child fetches the actual text element:
Dim text = CType(t.Rows(getrow).Cells(getcol).Children.First().Children.First().Children.First(), Text)
'' Get the parent run:
Dim run = CType(text.ParentContent, Run)
'' Mark the found cell with bold/italic font:
Dim rs1 = doc.Styles.Add("cell hi-light", StyleType.Character)
rs1.Font.Bold = True
rs1.Font.Italic = True
run.Style = rs1
'' Add the fetched text from cell (2,0) before the document's opening paragraph,
'' using the same character style:
Dim pp = header.GetRange().Paragraphs.Insert(
$"Text from cell at row {getrow + 1}, col {getcol + 1} (drawn with bold/italic font): """, InsertLocation.Before)
Dim r = pp.GetRange().Runs.Add(text.Value)
r.Style = rs1
pp.GetRange().Runs.Add(""".")
'' Done:
Return doc
End Function
End Class