Search code examples
c#ms-wordword-interop

How to get the sort type (ascending/descending) of a table in Microsoft Word by C#?


I have a Word document with 2 tables. The second table has 5 columns. This table is sorted by the fourth column. Now, I want to know which sort type is applied in this table by using C#.

I have tried to search on the internet, but I can only find the Sort method in Microsoft's documentation and I don't know how to begin with it (https://learn.microsoft.com/en-us/dotnet/api/microsoft.office.interop.word.table.sort?view=word-pia).

    int result;
    MSWord.Document docx;

    void SortTable()
            {
                if (docx.Tables.Count < 1)
                {
                    result = 0;
                }
                else {
                    MSWord.Table table = docx.Tables[2];
                }
    }


Solution

  • Word doesn't store whether a table has been sorted, and how, as a property. When you think about it, it wouldn't make much sense because any edit could change the table's "sorted state".

    Sort is simply a method that creates a "snap-shot" at the moment it is applied. It does not return a value.

    If code is sorting a table, it would be possible to save what kind of sort was performed at the moment it's executed.

    To evaluate whether and how a table has been sorted the only possibility is to check and compare the content of the table cells to determine whether they're in ascending, descending or no order.