In a Word document, I can move to the next cell by using the TAB key. And when I get to the last cell in the last row of the table, pressing the TAB key generates a new row. I want to do the same thing in Aspose.Words. I have a document template with a bookmark in the first cell of the table. After writing the value in the first cell of the table I want to move to the next cell. I’ve tried builder.Write("\t") and builder.Write("\n") but the write position stays in the first cell.
How do I move to the next cell in a table?
Hi
Thanks for your inquiry. You should use DocumentBuilder.MoveToCell method to move between cells. Please see the following link for more information.
https://reference.aspose.com/words/net/aspose.words/documentbuilder/movetocell/
Also if you have bookmark in the first cell of your table you can try using the following code.
// Open document and create DocumentBuilder
Document doc = new Document(@"Test099\in.doc");
DocumentBuilder builder = new DocumentBuilder(doc);
// Move documentBuilder cursor to the bookmark
builder.MoveToBookmark("myBookmark");
if (builder.CurrentNode.GetAncestor(NodeType.Row) != null)
{
// Create a clone of emty row
// this will be needed for inserting additional rows
Row emptyRow = (Row)builder.CurrentNode.GetAncestor(NodeType.Row).Clone(true);
// Also we should get Parant table
Table mainTable = (Table)builder.CurrentNode.GetAncestor(NodeType.Table);
// For example we would like to insert 100 items
// But Table inside document has only one row
// and row has 5 cells
for (int i = 0; i < 100; i++)
{
// Insert some value
builder.Write(String.Format("value of cell #{0}", i));
// Now we should move cursor to the next cell
// We get cell where cursor is placed now
// And move cursor to the next cell
Cell currentCell = (Cell)builder.CurrentParagraph.GetAncestor(NodeType.Cell);
// Check whether there is next cell in the current row
if (currentCell.NextSibling != null)
{
// If so move document builder cursor to the next cell
builder.MoveTo((currentCell.NextSibling as Cell).FirstParagraph);
}
// Otherwise move cursor to the next row
else
{
// Get current Row
Row currentRow = currentCell.ParentRow;
if (currentRow.NextSibling != null)
{
builder.MoveTo((currentRow.NextSibling as Row).FirstCell.FirstParagraph);
}
// If there is no next row we should insert new row
else
{
mainTable.AppendChild(emptyRow.Clone(true));
builder.MoveTo(mainTable.LastRow.FirstCell.FirstParagraph);
}
}
}
}
// Save result document
doc.Save(@"Test099\out.doc");
I hope this could help you.
Best regards.
Thanks for the detailed explanation.