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

时间:2019-07-07 15:09:54

标签: python openpyxl

Excel工作表中的一系列单元格可以设置为表格格式。 Openpyxl在documentation中提供了有关如何编写此类表的示例。

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

一个简单的openpyxl语句,当提供表名时,它将把表读入一个openpyxl Table对象。

3 个答案:

答案 0 :(得分:0)

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

tables = sheet._tables

然后可以通过其tableName搜索所需的表,并返回范围:

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)

答案 1 :(得分:0)

以下函数从表名称定义的范围中读取单元格值,并返回一个元组,其中包含列标题列表和数据字典。这对于创建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)

答案 2 :(得分:0)

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

要获取 openpyxl.worksheet.table.Table 对象,您可以执行以下操作:

sheet.tables.get('MyTable')

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

相关问题