Rakesh Sharma
Rakesh Sharma

Reputation: 35

How to check for blank cell in excel in python?

I have a workbook of 12 sheet and every sheet has some value in column A. All the useful information starts from row 9 column 0 of every sheet. Once the cell (AX,0) has no data it should move to the next sheet. Here num is the number of sheet in the workbook. The code is below:

workbook = xlrd.open_workbook('example.xlsx')
row = 9
num = 0
col = 0

while True:
    worksheet = workbook.sheet_by_index(num)
    if worksheet.cell(row, col).value != xlrd.empty_cell.value:
        worksheet.cell(row, col).value
        row+=1
    else:
        if num != 12:
            num = num + 1
            row = 9

I am getting the below error:

File "", line 4, in if worksheet.cell(row, col).value != xlrd.empty_cell.value: File "C:\Python27\lib\site-packages\xlrd\sheet.py", line 412, in cell self._cell_types[rowx][colx], IndexError: list index out of range

Help me!!!

Upvotes: 2

Views: 4469

Answers (2)

User15239563
User15239563

Reputation: 391

I think you should add a break in the While loop, so you dont loop infinitely.

if num != 12:
    num = num + 1
    row = 9
else:
    break

Edit

Another problem is with your if statement of checking empty cell. Based in Openpyxl check for empty cell The problem is, that the "if" is true all the time, so row is unlimitely incremented and you get index out of range error.

If you want to check for not empty cell use this

if worksheet.cell(row, col).value != None:
    # Do stuff

Upvotes: 0

Ahlam
Ahlam

Reputation: 31

I think the problem is that if the program enter the "else" block will be stock there because there in no way out so I suggest to either use ( break) or (return)

Upvotes: 0

Related Questions