使用xlrd库读取Excel文件时如何检测单元格是否为空? [英] How to detect if a cell is empty when reading Excel files using the xlrd library?

查看:3119
本文介绍了使用xlrd库读取Excel文件时如何检测单元格是否为空?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用函数 row_values col_values 处理Excel文件:

  import xlrd 
workbook = xlrd.open_workbook(filename)
sheet_names = workbook.sheet_names()
在sheet_names中的sheet_name:
sheet = workbook.sheet_by_name(sheet_name)
#...
row_values = sheet.row_values(rownum)
#...
col_values = sheet.col_values(colnum)
/ pre>

例如,我将col_values列为。如果我在一些列中遇到空单元呢?例如,单元格(1,1)不为空,单元格(1,2)为空,单元格(1,3)不为空?如何检测单元格(1,2)是否为空?



这是真的,我得到一个空字符串的列表作为一个空单元格的值(对于生成Excel文件的大多数知名程序)?

解决方案

您可以明确地检查 (xlrd.XL_CELL_EMPTY,xlrd.XL_CELL_BLANK)中的sheet.cell_type(rowno,colno),但文档的值将为 u'其中



而不是使用 row_values ,您也可以使用行(n)它返回一个单元格对象的列表,它们具有 .value .cell_type 属性。


I handle Excel files using the functions row_values and col_values:

import xlrd
workbook = xlrd.open_workbook( filename )
sheet_names = workbook.sheet_names()
for sheet_name in sheet_names:
  sheet = workbook.sheet_by_name( sheet_name )    
  # ...
  row_values = sheet.row_values( rownum ) 
  # ...
  col_values = sheet.col_values( colnum )

For example, I get col_values as list. What if I meet an empty cell in some column? For example a cell (1,1) is not empty, a cell (1,2) is empty and a cell (1,3) is not empty? How can I detect that the cell (1,2) is empty?

Is this true that I get a list with an empty string as a value of an empty cell (for most well-known programs which generate Excel files)?

解决方案

You could be explicit and check that sheet.cell_type(rowno, colno) in (xlrd.XL_CELL_EMPTY, xlrd.XL_CELL_BLANK) but the docs state the value will be u'' where those are the case anyway.

Instead of using row_values, you could also use row(n) which returns a list of Cell objects which have .value and .cell_type attributes.

这篇关于使用xlrd库读取Excel文件时如何检测单元格是否为空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆