Openpyxl check for empty cell

openpyxl seems to be a great method for using Python to read Excel files, but I ran into a persistent problem. I need to determine if a cell is empty or not, but cannot compare any of the cell properties. I tried to cast as a string and use "" but that didn't work. The cell type when it is empty is None or NoneType but I cannot figure out how to compare the object with this.

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

+11
source share
4 answers

To do something when the cell is not empty, add:

 if cell.value: 

which in python is the same as if the cell value was not None (for example: if not cell.value == None :)

Note. To avoid checking empty cells, you can use

 worksheet.get_highest_row() 

and

 worksheet.get_highest_column() 

I also found this useful (although it may not be a good solution) if you want to use the contents of the cell as a string, regardless of the type you can use:

 unicode(cell.value) 
+21
source

It worked for me.

 if cell.value is None: print("Blank") else: print("Not Blank") 
+13
source

 if cell.value is None: 

This is the best option to use in this case.

if you want to use it in iteration, you can use it as follows:

 ws=wb.active names=ws['C'] for x in names: if x.value is None: break print(x.value) 

The problem with ws.max_column and ws.max_row is that it will also consider empty columns that ws.max_column ws.max_row on target.

0
source

You can change the cell or cells you want to check. You can also encode, for example:

 import openpyxl wb = openpyxl.load_workbook("file.xlsx") sheet = wb.get_sheet_by_name('Sheet1') if sheet.cell(row = 1, column=7).value == None: print("Blank") else: print("No blank") 
-2
source

All Articles