Thursday, December 8, 2011

Getting Table Cells Row by Row

Once you have a table identifier, you can access each of the cells within that table. This post focuses on accessing cells from left to right and top to bottom.

To do so:
  1. Get the first row in the table using the Tbl property FirstRowInTbl.
  2. Get the first cell in that row using the Row property FirstCellInRow.
  3. While there are additional cells, get each using the Cell property NextCellInRow.
  4. While there are additional rows, get each using the Row property NextRowInTbl.
Here is a script that does just that and writes to each cell in the order visited.

var doc, table, row, cell, cellNum = 0;

doc = app.ActiveDoc;
table = doc.SelectedTbl;
row = table.FirstRowInTbl;
while (row.ObjectValid()) { //traverse rows
    cell = row.FirstCellInRow;
    while (cell.ObjectValid()) { //traverse cells in row
        cellNum++;
        var tLoc = new TextLoc();  //create text location object
        tLoc.obj = cell; //make it a cell
        tLoc.offset = 0; // insert at the start of the cell
        doc.AddText(tLoc, "Cell "  + cellNum);
        cell = cell.NextCellInRow;
    }
    row = row.NextRowInTbl;
}

Note: The first row in a table can be a header row (as shown) or a body row if no header exists.

No comments:

Post a Comment