这是我当前的代码。如您所见,我通过指定列索引从每行的每个单元格中获取值。
for row_cells in sheet.iter_rows(min_row=1, max_row=10):
object = {"key1": str(row_cells[1].value), "Key2": str(row_cells[3].value),
"Key3": str(row_cells[4].value), "Key4": str(row_cells[2].value),
"Key5": str(row_cells[5].value)}
现在,在给定的excel工作表中,第一行始终包含每一列的标题。
有没有一种方法,我不用指定索引,而是指定列的名称,然后在单元格中获取一个值。 .upper()
方法确实为我们提供了列的最上方单元格的值。
答案 0 :(得分:1)
您可以通过迭代列来做到这一点。检查您需要的列。并获取值。
import openpyxl
book = openpyxl.load_workbook(path)
sheet = book['Data']
column_name = 'Username'
for column_cell in sheet.iter_cols(1, sheet.max_column): # iterate column cell
if column_cell[0].value == column_name: # check for your column
j = 0
for data in column_cell[1:]: # iterate your column
print(data.value)
break
答案 1 :(得分:0)
您可以通过首先构建字典来实现此目的,其中的键是列名,值是列号。然后,使用词典将名称从数字转换为数字。
import openpyxl
workbook = openpyxl.load_workbook('Data/Test01.xlsx')
worksheet = workbook['Sheet1']
## Create a dictionary of column names
ColNames = {}
Current = 0
for COL in worksheet.iter_cols(1, worksheet.max_column):
ColNames[COL[0].value] = Current
Current += 1
## Now you can access by column name
## (My data has a column named 'Dogs')
for row_cells in worksheet.iter_rows(min_row=1, max_row=4):
print(row_cells[ColNames['Dogs']].value)