如何停止在第一个空行使用xlrd读取电子表格?

我使用xlrd通过目录结构嗅探,并拉出电子表格,读取第二行(第一行)到“做的东西”。 问题是,我不知道如何停止在第一个空行阅读/打印。 我知道行不是“空”对象,但我会感谢一些帮助,显示如何检查所有单元格是否为空。 以下是我正在使用的代码:

import xlrd import os def excel_file_filter(filename, extensions=['.xls', '.xlsx']): return any(filename.endswith(e) for e in extensions) def get_filenames(root): filename_list = [] for path, subdirs, files in os.walk(root): for filename in filter(excel_file_filter, files): filename_list.append(os.path.join(path, filename)) return filename_list spreadsheets = get_filenames('C:\\Temp') for s in spreadsheets: with xlrd.open_workbook(s) as wb: cs = wb.sheet_by_index(0) num_cols = cs.ncols for row_index in range(1, cs.nrows): print('Row: {}'.format(row_index)) for col_index in range(0, num_cols): cell_object = cs.cell(row_index, col_index) if cell_obj is not xlrd.empty_cell: print('Col #: {} | Value: {}'.format(col_index, cell_obj)) 

最终发生的事情是,它一直打印几乎1000行,当只有第一个说,25行有内容。 电子表格之间的内容数量是不同的,所以一个通用的解决scheme(不依赖于其他可选库)帮助我理解如何检测一个空行然后中断,将不胜感激。

首先:要获取单元格值,然后检查它是否为空,请使用问题答案中介绍的方法之一如何在使用xlrd库读取Excel文件时检测单元格是否为空?

  1. 当使用cell_val= cs.cell(row_index, col_index).value获取值:
    • 要检查它是否为空:只要写if cell_vel == ''
  2. 当使用cell_object = cs.cell(row_index, col_index)获取值:
    • 要检查它是否为空:
      -first获取cell_type = cs.cell_type(row_index, col_index)
      然后检查if cell_type == xlrd.XL_CELL_EMPTY

第二:要检查整行是否为空,您可以执行以下操作:

  1. 定义一个计数器(count_empty = 0)来计算row&boolean(empty_cell = False)
  2. 检查单元格是否为空
    如果是>增加计数器并将empty_cell更改为True
    如果不是>设置empty_cell False
  3. 检查empty_cell是否为False>打印单元格的值
  4. 循环遍历行中的列
    如果count_empty等于列数>意味着整行是空的>中断和停止循环行

代码:

 # define empty_cell boolean empty_cell= False with xlrd.open_workbook(s) as wb: cs= wb.sheet_by_index(0) num_cols= cs.ncols num_rows= cs.nrows for row_index in range(1, num_rows): # set count empty cells count_empty = 0 print('Row: {}'.format(row_index)) for col_index in range(0,num_cols): # get cell value cell_val= cs.cell(row_index, col_index).value # check if cell is empty if cell_val== '': # set empty cell is True empty_cell = True # increment counter count_empty+= 1 else: # set empty cell is false empty_cell= False # check if cell is not empty if not empty_cell: # print value of cell print('Col #: {} | Value: {}'.format(col_index, cell_val)) # check the counter if is = num_cols means the whole row is empty if count_empty == num_cols: print ('Row is empty') # stop looping to next rows break 

注意:我使用了第一个方法cell_val= cs.cell(row_index, col_index).value来获取单元格的值,我发现它比较简单。 如果您想使用其他方法更改以下内容:

  cell_val= cs.cell(row_index, col_index) # remove .value cell_type= cs.cell_type(row_index, col_index) # add this line # check if cell is empty if cell_type == xlrd.XL_CELL_EMPTY: # change if cell_val== '': 

帮助我了解如何检查单元格是否为空的其他链接:
xlrd.XL_CELL_EMPTY和使用XLRDvalidation单元格值