如何在第一个空行停止阅读带有 xlrd 的电子表格?

How to stop reading a spreadsheet with xlrd at the first empty row?

我正在使用 xlrd 嗅探目录结构并提取电子表格,读取第二行(第 1 行)一直到 "do stuff." 问题是我不知道如何停止 reading/printing 在第一个空行。我知道行不是 "empty" 对象,但我希望能为您提供一点帮助来说明如何检查所有单元格是否为空。这是我正在使用的代码:

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 行中有内容。电子表格之间的内容量各不相同,因此,如果有一个通用解决方案(不依赖于其他可选库)可以帮助我了解如何检测空行然后中断,我们将不胜感激。

首先: 要获取单元格值然后检查它是否为空,请使用问题 How to detect if a cell is empty when reading Excel files using the xlrd library?

的答案中解释的方法之一
  1. 使用cell_val= cs.cell(row_index, col_index).value取值时:
    • 检查是否为空:只需写if cell_vel == ''
  2. 使用cell_object = cs.cell(row_index, col_index)取值时:
    • 检查是否为空:
      - 首先得到 cell_type cell_type = cs.cell_type(row_index, col_index)
      - 然后检查 if cell_type == xlrd.XL_CELL_EMPTY

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

  1. 定义一个计数器 (count_empty=0) 来计算行中空单元格的数量 & 布尔值 (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 and

要检查单个单元格是否为空,请检查其 ctype attribute. To check an entire row, use the all function on a list comprehension:

workbook = xlrd.open_workbook(filepath)
sheet = workbook.sheets()[0]
rows = sheet.get_rows()
next(rows) # skip first row
for row in rows:
    if all([cell.ctype in (xlrd.XL_CELL_EMPTY, xlrd.XL_CELL_BLANK)
            for cell in row]):
        break
    # process this non-empty row here...