如何使用 Openpyxl 访问 Excel 表格的特定单元格

问题描述 投票:0回答:2

我尝试按名称引用 Excel 表,然后按名称引用表中的列,最后迭代该列中的所有行。

到目前为止,我已经成功将 openpyxl 连接到我的电子表格并通过直接查看单元格来读取值。但是,我更愿意使用表名称和列名称,而不是硬编码的单元格坐标。

# Open my excel file, and save it as a variable to use later
input_excel_file = pyxl.load_workbook(path_backup_excel_file, data_only=True)
# Open the specific sheet from the excel file
sheet_panels_to_run = input_excel_file['Panels to Run']

# This reads values fine, but does not use the table.
print(sheet_panels_to_run['a2'].value)

# Save the table to a variable. This part works fine.
request_table = sheet_panels_to_run.tables['RequestTable']

# I'm able to narrow down to a specific column, but not sure how to see values from its rows yet.
print(request_table.tableColumns['Panel Name'])
python excel openpyxl
2个回答
0
投票

您可以使用 openpyxl 库迭代 Excel 表中特定列的行,首先获取所需列的列索引,然后使用循环迭代该列的行。以下是如何执行此操作的示例:

# Open my excel file, and save it as a variable to use later
input_excel_file = pyxl.load_workbook(path_backup_excel_file, data_only=True)
# Open the specific sheet from the excel file
sheet_panels_to_run = input_excel_file['Panels to Run']

# Save the table to a variable. This part works fine.
request_table = sheet_panels_to_run.tables['RequestTable']

# Get the index of the desired column
column_index = request_table.tableColumns['Panel Name'].index + 1

# Iterate through the rows of the desired column
for row in range(request_table.ref[0][1]+1, request_table.ref[1][1]+1):
    cell_value = sheet_panels_to_run.cell(row=row, column=column_index).value
    print(cell_value)

此代码将迭代 RequestTable 表的 Panel Name 列中的所有行并打印它们的值。


0
投票

不幸的是,openpyxl

Table
类似乎没有方便的内置方法来迭代其单元格。然而,以下应该有效:

from openpyxl.utils.cell import range_boundaries
import openpyxl as pyxl  # v3.0.10

# Access excel sheet
input_excel_file = pyxl.load_workbook(path_backup_excel_file, data_only=True)
sheet_panels_to_run = input_excel_file['Panels to Run']

# Access named table
request_table = sheet_panels_to_run.tables['RequestTable']

# Get range boundaries of table
min_col, min_row, max_col, max_row = range_boundaries(request_table.ref)

# Construct headers lookup dictionary
headers = {
    col.name: col_idx
    for (col_idx, col)
    in enumerate(request_table.tableColumns)
}

# Get relative column index of target column
target_col_idx = headers['Panel Name']

# Loop over all data values in target column
for i in range(min_row + 1, max_row + 1):
    value = sheet_panels_to_run.cell(i, min_col + target_col_idx).value
    print(value)
© www.soinside.com 2019 - 2024. All rights reserved.