Add rows to existing table keeping format of the row


#1

My users create a table within Word which consists of a header row with the desired column names and one empty row which is formatted as they want the inserted rows to be formatted.

Using a comma delimited string of values I populate the row with data. Each new row added keeps the formatting of the previous row.

Using the Documentation and Forums I have been able to work out how to find the table and add a row with the data from the string correctly placed into each column but I lose the formatting. Is there a way to easily "Copy" the format of an exsiting row when adding a new row programatically.

Something like this would be great

bool copyFormatting = true;
table.InsertAfter(new Row(), table.LastRow, copyFormatting);
This would add the new row after the last row in the table and copy all the formatting of the row it is inserting after.

OR
perhaps allow a RowFormat to be passed into the Insert function which is used to format the new row that is added?

table.InsertAfter(new Row(), table.LastRow, table.LastRow.RowFormat);

I know there is the Mail Merge functionality to work with tables but I cannot use Mail Merge as I have to be able to work with existing functionality.

All help is greatly appreciated.

Jeff


#2

You can use Row.Clone method to create row with the same formatting.

Unfortunately, right now cloning of the table row does not preserve formatting if the row cells are empty.

So all you need to do is putting some dummy text in the template row cells. Then, the following code will work fine.

// searching for a first table in document

Table table = (Table)doc.GetChild(NodeType.Table, 0, true);

if(table==null) return; //exit if table not found

Row row = table.Rows[1]; //taking the second row as a template

row = (Row)row.Clone(true); // deep cloning

table.Rows.Add(row); // adding

foreach(Cell cell in row.Cells) {

// changing text

((cell.Paragraphs[0] as Paragraph).Runs[0] as Run).Text = "real text";

}