openpyxl 遍历特定的列
openpyxl iterate through specific columns
for row_cells in sheet.iter_rows(min_col=1, max_col=8):
for cell in row_cells:
print('%s: cell.value=%s' % (cell, cell.value))
上面的代码片段 returns 从第 1 列到第 8 列的所有列。我只需要这两列中的值。
是否可以只第 1 列和第 8 列?我还没弄明白。
有两种方法:
for row in range(2,worksheet.max_row+1):
for column in [column_3_name, column_8_name]:
cell_name = "{}{}".format(column, row)
process(worksheet[cell_name].value) # Process it
注意这会占用大量内存,为每个单元格分配内存。看:
https://openpyxl.readthedocs.io/en/2.5/tutorial.html(尤其是第一个警告)。
我会选择做你现在正在做的事情:
for row_cells in sheet.iter_rows(min_col=1, max_col=8):
for cell in row_cells:
# Check for column name here.
您没有义务拥有内部循环:
for row_cells in sheet.iter_rows(min_col=1, max_col=8):
print('%s: cell.value=%s' % (row_cells[0], row_cells[0].value))
print('%s: cell.value=%s' % (row_cells[-1], row_cells[-1].value))
更好的方法可能是将迭代器压缩到这两列上:
for c1, c8 in zip(sheet.iter_rows(min_col=1, max_col=1), sheet.iter_rows(min_col=8, max_col=8)):
print('%s: cell.value=%s' % (c1, c1.value))
print('%s: cell.value=%s' % (c8, c8.value))
for row_cells in sheet.iter_rows(min_col=1, max_col=8):
for cell in row_cells:
print('%s: cell.value=%s' % (cell, cell.value))
上面的代码片段 returns 从第 1 列到第 8 列的所有列。我只需要这两列中的值。 是否可以只第 1 列和第 8 列?我还没弄明白。
有两种方法:
for row in range(2,worksheet.max_row+1):
for column in [column_3_name, column_8_name]:
cell_name = "{}{}".format(column, row)
process(worksheet[cell_name].value) # Process it
注意这会占用大量内存,为每个单元格分配内存。看: https://openpyxl.readthedocs.io/en/2.5/tutorial.html(尤其是第一个警告)。
我会选择做你现在正在做的事情:
for row_cells in sheet.iter_rows(min_col=1, max_col=8):
for cell in row_cells:
# Check for column name here.
您没有义务拥有内部循环:
for row_cells in sheet.iter_rows(min_col=1, max_col=8):
print('%s: cell.value=%s' % (row_cells[0], row_cells[0].value))
print('%s: cell.value=%s' % (row_cells[-1], row_cells[-1].value))
更好的方法可能是将迭代器压缩到这两列上:
for c1, c8 in zip(sheet.iter_rows(min_col=1, max_col=1), sheet.iter_rows(min_col=8, max_col=8)):
print('%s: cell.value=%s' % (c1, c1.value))
print('%s: cell.value=%s' % (c8, c8.value))