I have a document containing lots of tables. I want to modify those tables using C# and Microsoft.Office.Interop.Word. I read that I can iterate trough all tables using the Tables interface.
Question: is it possible to give the table a name/ID and access the table by its name? (like with shapes in Powerpoint automation).
Question 2: If it's not possible with Microsoft.Office.Interop.Word, do the alternatives like Aspose Words offer a more convenient way?
is it possible to give the table a name/ID and access the table by its name?
The Table object does offer an ID property however this is only documents saved as a web page. I am assuming this is not what you want.
It is still possible however it is not provided by the API; you need to create this feature yourself. There are two ways:
One: Using Interop, you can retrieve the table's hashcode which (hopefully) returns a unique ID. For example:
Word.Application wordApp = new Word.Application();
Word.Document wordDoc = wordApp.Documents.Open(@"C:\Users\username\Documents\HasTables.docx");
var tableID = wordDoc.Tables[1].GetHashCode();
A thorough solution might be to store the IDs of all tables in the document within a Dictionary or another collection type which has a map of key/value pairs. Now note that these IDs do not persist across Word sessions...so if you need to be able to identify a table beyond the same session, you will need to another method.
Two: Using OpenXML (for .docx format) and/or WordML (for Word 2003 XML, if you cannot simply upgrade the ocument to .docx) create your own Id or Name attribute for each w:tbl element. You can disambiguate by using your own namespace. This will also persist across Word sessions. This is a different world then Interop, but in my opinion, is the much better route (Performance, available documentation).
If it's not possible with Microsoft.Office.Interop.Word, do the alternatives like Aspose Words offer a more convenient way?
No, Aspose does not offer anything like this in their TableCollection or Table objects.