Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (18.4k points)

I am trying to run a simple piece of code (Python 3.6) to convert a range of cells in an excel worksheet into a list. Here is the code:

import openpyxl

wb_d = openpyxl.load_workbook('example.xlsx')

ws = wb_d.active

# iterate through all rows in specific column openpyxl

mylist = []

for row in ws.iter_rows('A{}:A{}'.format(ws.min_row,ws.max_row)):

    for cell in row:

        mylist.append(cell.value)

print(mylist)

I am getting the below error:

Traceback (most recent call last):

  File "PycharmProjects/Excel/list_generator.py", line 7, in <module>

    for row in ws.iter_rows('A{}:A{}'.format(ws.min_row,ws.max_row)):

  File "venv\Excel\lib\site-packages\openpyxl\worksheet\worksheet.py", line 438, in _cells_by_row

    for row in range(min_row, max_row + 1):

TypeError: 'str' object cannot be interpreted as an integer

I also tried defining the range of cells as 'A1: A10' and that threw me an error. 

1 Answer

0 votes
by (36.8k points)
edited by

The input parameters for the iter_rows() must be integers.

for row in ws.iter_rows('A{}:A{}'.format(ws.min_row,ws.max_row))

with

for row in ws.iter_rows(ws.min_row,ws.max_row)

If you are a beginner and want to know more about Python the do check out the Data Science with Python Course 

Browse Categories

...