How to find homany tables are there in the word document

Hi,


I have tried out the example to extract contain from the table in a document.

I have documents which contain tables but I don’t know the number of tables inside the document and I want to extract content from the tables.

How to find the total number of tables inside the document so I can pass the index paramenter in the following statment dynamically i.e if 1 table then 0 ,if 2 tables then 1 so on…

This is for 1 table.
Table table = (Table) doc1.getChild(NodeType.TABLE, 0, true);

Please help me in this matter.

Hi Crimson,


Thanks for your inquiry. You can use the following statement to retrieve all tables in Word document:

NodeCollection tables = doc.getChildNodes(NodeType.TABLE, true);

Hope, this helps.

Best regards,

Hi,

Thanks for yout reply.

I have used the following code and I have 3 tables in my document.

NodeCollection allTables = doc1.getChildNodes(NodeType.TABLE, true);
int tableIndex = allTables.indexOf(table);
System.out.println(tableIndex);

The output is:
0

The output should be 2 as index is 0 based.

Hi Crimson,


Thanks for your inquiry. Could you please attach your input Word document here for testing? We will investigate the issue on our end and provide you more information.

Best regards,

Hi,

PFA test file.

Hi Crimson,


Thanks for your inquiry. When using the latest licensed version of Aspose.Words for Java 16.2.0, the following code correctly returns 3 tables in your document.

Document doc = new Document(getMyDir() + “testtable.doc”);
NodeCollection allTables = doc.getChildNodes(NodeType.TABLE, true);
System.out.println(allTables.getCount());

So, you can use a loop from 0 to 2 and get each table in “allTables” collection. If we can help you with anything else, please feel free to ask.

Best regards,

Hi Awais,


Thanks for you reply it works for me.