问题描述
我是编程新手,目前正在学习python和openpyxl进行excel文件操作。 我正在编写一个脚本来帮助更新维修数据库,该数据库在Excel工作表中选择特定的记录。 我已经编写了一个脚本,可以获取需要更新的excel数据的行号,但是现在的挑战是如何通过迭代在行列表(记录)中创建列表。
例如,我发现我需要第22、23、34和35行的数据。有没有一种方法可以获取这些行的数据而不必为该行的每个实例更改min_row和max_row数?
我需要重写的代码部分是:
# copy the record on the rows of the row numbers found above.
rows_records = []
row_record = []
for row_cells in ws2.iter_rows(min_row=23,max_row=23,min_col=1,max_col = 6):
for cell in row_cells:
row_record.append(cell.value)
rows_records.append(row_record)
print(row_record)
print(rows_records)
解决方法
import openpyxl
book = openpyxl.load_workbook('numbers.xlsx')
sheet = book.active
rows = sheet.rows
values = []
your_row_indices = [21,22,23]
for row in rows[your_row_indices]:
for cell in row:
values.append(cell.value)
,
由于openpyxl返回了生成器,因此您必须将其转换为列表才能访问特定的索引
import openpyxl
workbook = openpyxl.load_workbook('numbers.xlsx')
worksheet = workbook .active
rows = list(worksheet.iter_rows(max_col=6,values_only=True))
values = []
row_indices = [21,23,34,35]
for row_index in row_indices:
values.append(rows[row_index])