Accessing a table by name in Word using c#

后端 未结 1 536
囚心锁ツ
囚心锁ツ 2021-01-23 04:49

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 Tabl

1条回答
  •  迷失自我
    2021-01-23 05:14

    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.

    0 讨论(0)
提交回复
热议问题