Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Openpyxl check for empty cell

Tags:

openpyxl seems to be a great method for using Python to read Excel files, but I've run into a constant problem. I need to detect whether a cell is empty or not, but can't seem to compare any of the cell properties. I tried casting as a string and using "" but that didn't work. The type of cell when it is empty is None, or NoneType but I can't figure out how to compare an object to that.

Suggestions? I understand openpyxl is under development, but maybe this is more a general Python problem.

like image 348
MechEngineer Avatar asked Oct 26 '11 19:10

MechEngineer


People also ask

How do I check if a cell is empty in Excel using Python XLRD?

Find Empty and Non-Empty Cells of the table in an excel file in Python. import xlrd empty=0 filled=0 path="Excel. xlsx" wb=xlrd. open_workbook(path) sheet=wb.

How do I get Max rows in Openpyxl?

To find the max row and column number from your Excel sheet in Python, use sheet. max_row and sheet. max_column attributes in Openpyxl. Note - If you update a cell with a value, the sheet.


1 Answers

To do something when cell is not empty add:

if cell.value: 

which in python is the same as if cell value is not None (i.e.: if not cell.value == None:)

Note to avoid checking empty cells you can use

worksheet.get_highest_row() 

and

worksheet.get_highest_column() 

Also I found it useful (although might not be a nice solution) if you want to use the contents of the cell as a string regardless of type you can use:

unicode(cell.value) 
like image 59
Aron Kisdi Avatar answered Nov 09 '22 03:11

Aron Kisdi