Python for loop using openpyxl

8.1k Views Asked by At

I'm using the openpyxl package to make a simple tool that will be used to take excel inputs of large spreadsheets and make smaller more usable ones. I have tried using many different types of loops for this logic, but I still can't get it to work. The objective is to find any cell that has a value of 1 and copy the cell directly next to it onto a new workbook. Here's my code:

# for loop data logic
data = default['Default']
n = 1
for i in range(0,1000):
    for j in range(0,0):
        ds = data.cell(row = i, column = j)               
        if  ds == 1:
            n = n + 1
            ds.cell(row = i, column = 0).value = separated.cell(row = n, column = 0).value

NOTE: The data that I am inputting has many cells that have a numerical value of 1 in the first column. That is the one column this loop is testing for. I've been testing the code with a simple print command:

print(separated['A2'].value)

Which prints that there is no present value in the cell by printing "None." Again, I've tried two or three different for loops for this logic, and while they have all run without errors, none ever seem to change any values in the "separated" worksheet. Any and all help is appreciated.

2

There are 2 best solutions below

3
On BEST ANSWER

There are several errors in the code. The inner loop will never run because range(0, 0) is empty. Furthermore, openpyxl uses 1-indexing: A1 == cell(row=1, column=1) so ws.cell(row=0, column=0) would raise an exception if it ever executed.

However, you should probably just use ws.get_squared_range(min_col, min_row, max_col, max_row) to get a generator of the cells you want to look at.

0
On

I think you can scan like this, scanning for value or text. Example:

for col in sheet['A1:B100']:

        for cell in col:

            if cell.value == '1':

                print("Lo halle")   

Then you proceed to copy the information in the new workbook.

Good luck