Free Support Forum - aspose.com

Looping Through All Cells in a Table

Hi,

Please can you tell me if it is possible to loop through all cells in a table using Aspose.Words? I know Aspose.Words can support this by looping through all of the cells in a row, but I am adapting some existing code that uses Word Automation to loop through all the cells in a whole table, and if I could replicate this in Aspose.Words then it would save me a considerable amount of rewriting.

Thanks for your help

Hi

Thanks for your request. Try to use the following code example.

Document doc = new Document(@"189_94559_workaholicme\in.doc");

DocumentBuilder builder = new DocumentBuilder(doc);

NodeCollection cells = doc.FirstSection.Body.Tables[0].GetChildNodes(NodeType.Cell, true);

foreach (Cell cell in cells)

{

builder.MoveTo(cell.FirstParagraph);

builder.Write("test");

}

doc.Save(@"189_94559_workaholicme\out.doc");

Or the following

Document doc = new Document(@"189_94559_workaholicme\in.doc");

DocumentBuilder builder = new DocumentBuilder(doc);

foreach (Row row in doc.FirstSection.Body.Tables[0].Rows)

{

foreach (Cell cell in row.Cells)

{

builder.MoveTo(cell.FirstParagraph);

builder.Write("_test_");

}

}

doc.Save(@"189_94559_workaholicme\out.doc");

I hope that it will help you.

Best regards.

Thanks - that’s great. Last question - would you be able to tell me how I can find the row number that each cell belongs to? I think I would be able to use cell.parentrow.indexof, but I can’t seem to get the syntax working correctly. Many thanks

Hi

Thanks for your request. try to use the following code snippet.

int index = doc.FirstSection.Body.Tables[0].Rows.IndexOf(cell.ParentNode);

Best regards.

Fantastic - that works a treat, thanks. Can you tell me if I can do the same thing with Column numbers though? I need to be able to find out which row and column a cell belongs to. Using your previous example, I can now find the row number, but am not sure how to find the column number. Thanks again for your help

Hi

Try to use the following code snippet.

foreach (Cell cell in cells)

{

int index = doc.FirstSection.Body.Tables[0].Rows.IndexOf(cell.ParentNode);

int index2 = doc.FirstSection.Body.Tables[0].Rows[index].Cells.IndexOf(cell);

builder.MoveTo(cell.FirstParagraph);

builder.Write(String.Format("{0};{1}", index2.ToString(), index.ToString()));

}

Best regards.