简体   繁体   中英

Iterating Rows for Different Columns with Python and Openpyxl

I'm trying to iterate through rows in an Excel spreadsheet using openpyxl. What I'm trying to do is check if the cell in column A is empty for the current row, and if it is, I need to print the data that is in column B on that same row. Here is my code so far:

wb = openpyxl.load_workbook('worksheet.xlsx')
wb.active = 1 #Change the active sheet.
sheets = wb.sheetnames #The sheets.
currentSheet = wb[sheets[n]] #Chooses the current sheet from the workbook.

for row in currentSheet.iter_rows('A{}:A{}'.format(currentSheet.min_row, currentSheet.max_row)):
    for cell in row:
        if not cell.value:
            print(currentSheet['B''row'].value)

When I run this I get the following output:

  File "main.py", line 69, in get_callout
    print(currentSheet['B''row'].value)
  File "C:\Users\~\AppData\Local\Continuum\anaconda3\lib\site-packages\ope
pyxl\worksheet\worksheet.py", line 357, in __getitem__
    min_col, min_row, max_col, max_row = range_boundaries(key)
  File "C:\Users\~\AppData\Local\Continuum\anaconda3\lib\site-packages\ope
pyxl\utils\cell.py", line 135, in range_boundaries
    raise ValueError("{0} is not a valid coordinate or range")
ValueError: {0} is not a valid coordinate or range

Any help would be greatly appreciated!

EDIT I forgot to mention that I'm also using openpyxl 2.4.9 because 2.5.3 (the current version) won't let me open the Excel workbook that I need to use.

This is an example of when you should using Excel notation.

for (a, b) in currentSheet.iter_rows(max_col=2):
   if a.value is None:
       print(b.value)

Should work

I actually figured out a different way of doing it!

Here is my code for anybody that might stumble upon this in the future:

    for r in range(1, currentSheet.max_row):
        cell = currentSheet.cell(row=r, column=12)
        if cell.value is None:
            data = currentSheet.cell(row=r, column=2)
            print(data.value)

Basically what I was doing was checking to see if column L (12) was empty, and if it was I needed to print the value on the same row but in column B (2). Printing can obviously be changed with anything else (return or something else).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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