Working with Tables
As previously mentioned, both the Document and Range object have a Tables property that returns the Tables collection, which contains tables in the Document or Range. To add a Table, you can use the Tables collection's Add method, which takes a Range where you want to add the table, the number of rows and number of
Listing 8-41 shows code that adds and populates a small table. It uses the returned Table object's Rows property to get the Rows collection. It uses the
index
operator on the Rows collection to get an individual Row object. It then uses the Row object's Cells property to get the
Listing 8-41. A VSTO Customization That Creates and Populates a Simple Table
private void ThisDocument_Startup(object sender, EventArgs e)
{
Word.Range r = Range(ref missing, ref missing);
Word.Table t = r.Tables.Add(r, 5, 5, ref missing, ref missing);
for (int i = 1; i <= 5; i++)
{
for (int j = 1; j <= 5; j++)
{
t.Rows[i].Cells[j].Range.Text = String.Format(
"{0}, {1}", i, j);
}
}
}
The Table object's Cell method provides an easier way of getting to a Cell. The Cell method takes an
int
row and column parameter and returns a Cell object. Listing 8-42 shows the use of the Cell method along with the use of several auto-formatting techniques as we create a simple multiplication table. The Columns object's AutoFit method is used to resize the column widths to fit the contents of the cells. The Table object's set_Style method takes an
object
by reference that is set to the
Listing 8-42. A VSTO Customization That Creates a Multiplication Table
private void ThisDocument_Startup(object sender, EventArgs e)
{
Word.Range r = Range(ref missing, ref missing);
Word.Table t = r.Tables.Add(r, 12, 12, ref missing,
ref missing);
for (int i = 1; i <= 12; i++)
{
for (int j = 1; j <= 12; j++)
{
Word.Cell c = t.Cell(i,j);
if (i == 1 && j == 1)
{
c.Range.Text = "X";
}
else if (i == 1)
{
c.Range.Text = j.ToString();
}
else if (j == 1)
{
c.Range.Text = i.ToString();
}
else
{
int result = i * j;
c.Range.Text = result.ToString();
}
}
}
t.Columns.AutoFit();
object styleString = "Table Classic 2";
t.set_Style(ref styleString);
t.ApplyStyleLastRow = false;
t.ApplyStyleLastColumn = false;
}
|
Conclusion
This chapter has explored some of the most important objects in the Word object model. We use many of these objects in the Word examples in
This chapter has described these objects as defined by the primary interop assemblies for Word. Be aware, however, that VSTO extends some of these objects (Document, Bookmark, XMLNodes, and XMLNode) to add some additional functionality, such as data binding support. Part Three of this book, starting with Chapter 13, covers those extensions. |