简体   繁体   English

openpyxl - 遍历列和行以从工作表中间获取数据

[英]openpyxl - Iterate over columns and rows to grab data from middle of sheet

I'm reading the documentation for openpyxl, and I needed something a bit more specific and I wasn't sure if there's a way to do it using iter_rows or iter_cols.我正在阅读 openpyxl 的文档,我需要一些更具体的东西,我不确定是否有办法使用 iter_rows 或 iter_cols 来做到这一点。

In the docs, it said to do this to grab rows and cols:在文档中,它说这样做是为了获取行和列:

for row in ws.iter_rows(min_row=1, max_col=3, max_row=2):
  for cell in row:
    print(cell)

or或者

for col in ws.iter_cols(min_row=1, max_col=3, max_row=2):
  for cell in col:
    print(cell)

Doing this will give me A1, B1, C1 and so on or A1, A2, B1, B2, and so on.这样做会给我 A1、B1、C1 等等或 A1、A2、B1、B2 等等。

But is there a way to manipulate this so you can grab the data from another point in the sheet?但是有没有办法操纵它,以便您可以从工作表中的另一个点获取数据?

I'm trying to grab the cells from F3 to W3 for example.例如,我正在尝试将单元格从 F3 抓取到 W3。 But I'm not sure how many rows there are, there could be 5, there could be 10. So I would need to grab F4 to W4 and so on until I reach the last one which could be F10 to W10 or something.但我不确定有多少行,可能有 5 行,也可能有 10 行。所以我需要抓住 F4 到 W4,依此类推,直到我到达最后一个,可能是 F10 到 W10 或其他什么。

I understand how the iter_rows and iter_cols work but I haven't found a way to manipulate it to start elsewhere and to reach an end if there are no other values left?我理解 iter_rows 和 iter_cols 是如何工作的,但我还没有找到一种方法来操纵它从别处开始并在没有其他值的情况下结束? It appears I would have to define the max_rows to how many rows there are in the sheet.看来我必须将 max_rows 定义为工作表中有多少行。 Is there a way for it to check for the max amount of rows itself?有没有办法让它自己检查最大行数?

The biggest question I have is just how to iterate through the rows starting in the middle of the sheet rather than the beginning.我遇到的最大问题是如何遍历从工作表中间而不是开头开始的行。 It doesn't have to use iter_rows or iter_cols, that's just the part I was reading up on most in the documentation.它不必使用 iter_rows 或 iter_cols,这只是我在文档中阅读最多的部分。

Thank you in advance!先感谢您!

What's wrong with ws.iter_cols(min_row=3, min_col=6, max_col=23) for ws[F3:W…] ? 对于ws[F3:W…]ws.iter_cols(min_row=3, min_col=6, max_col=23)有什么问题? If no maximum is specified openpyxl will keep iterating as far as it can. 如果没有指定最大值,openpyxl将尽可能地继续迭代。

如果您希望能够在到达数据末尾时动态结束(例如,如果您最终得到超过 23 行/列的工作表),您可以设置max_row=ws.max_rowmax_col=ws.max_column

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM