如何使用 Openpyxl 读取现有工作表 table?

How to read an existing worksheet table with Openpyxl?

Excel 作品sheet 中的一系列单元格可能会被格式化为 table。 Openpyxl在documentation中提供了一个如何写这样的例子table.

如何使用 Openpyxl 读取现有的 Excel sheet table?

一个简单的 openpyxl 语句,当提供 table 名称时,会将 table 读入 openpyxl Table 对象。

Openpyxl 将所有工作表 table 存储在一个列表中。这些可以通过以下方式轻松阅读:

tables = sheet._tables

然后可以通过其table名称搜索所需的table,返回范围:

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

下面是一个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)

以下函数从 table 名称和 returns 包含列列表 headers 的元组和数据字典定义的范围中读取单元格值。这对于创建 Pandas DataFrame 很有用:

from openpyxl import load_workbook
import pandas as pd


    def read_excel_table(sheet, table_name):
    """
    This function will read an Excel table
    and return a tuple of columns and data

    This function assumes that tables have column headers
    :param sheet: the sheet
    :param table_name: the name of the table
    :return: columns (list) and data (dict)
    """
    table = sheet.tables[table_name]
    table_range = table.ref

    table_head = sheet[table_range][0]
    table_data = sheet[table_range][1:]

    columns = [column.value for column in table_head]
    data = {column: [] for column in columns}

    for row in table_data:
        row_val = [cell.value for cell in row]
        for key, val in zip(columns, row_val):
            data[key].append(val)

    return columns, data

book = load_workbook('table.xlsx')
ws = book.active

columns, data = read_excel_table(ws, 'Table1')
df = pd.DataFrame(data=data, columns=columns)

@So_tourist 的回答提供了获取 table 中单元格范围的方法,而不是所要求的 Table 对象。

要获取 openpyxl.worksheet.table.Table 对象,您可以这样做:

sheet.tables.get('MyTable')

注意:此答案适用于 openpyxl 3.0.6,不确定之前或之后的版本。