Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
841 views
in Technique[技术] by (71.8m points)

python - Openpyxl check for empty cell

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...