1

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.

1
  • did you print ds. see the value Commented Jun 18, 2015 at 13:44

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

I made the changes that you named it did help. I found on another website someone using the (0,0) notation for A1, and that was the root of the problem. With a little fidgeting I got it to work. Thanks for replying, I really appreciate it.
(0, 0) is, of course, standard indexing in Python but we found (1, 1) for A1 causes less problems.
To be precise, openpyxl switched to 1-indexing (in version 2.0 I think).
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.