Search code examples
pythonopenpyxl

How to read an existing worksheet table with Openpyxl?


A range of cells in an Excel worksheet may be formatted as a table. Openpyxl provides, in the documentation, an example of how to write such a table.

How would Openpyxl be used to read an existing Excel sheet table?

A simple openpyxl statement that, when provided with the table name, would read the table into an openpyxl Table object.


Solution

  • Openpyxl stores all the worksheet tables in a list. These can be easily read by:

    tables = sheet._tables
    

    Then it is possible to search for the desired table by its tableName, returning the range:

    for table in tables:
    if table.displayName == 'Table1':
        return table.ref
    

    Below is a MWE:

    from openpyxl import load_workbook
    book = load_workbook('table.xlsx')
    sheet = book.active
    
    tables = sheet._tables
    table_name = 'Table1'
    
    def find_table(table_name, tables):
        for table in tables:
            if table.displayName == table_name:
                return table.ref
    
    
    table_range = find_table(table_name, tables)