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

aus*_*der 5 python excel xlrd

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

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))
Run Code Online (Sandbox Code Playgroud)

最终发生的事情是它一直打印了近1000行,而只有第一行说,25行有内容.电子表格之间的内容量各不相同,因此可以理解一种通用解决方案(不依赖于其他可选库),这有助于我了解如何检测空行然后中断.

小智 9

第一步:要获取单元格值然后检查它是否为空,请使用问题答案中解释的方法之一如何在使用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 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
    如果不是> set 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     
Run Code Online (Sandbox Code Playgroud)

注意:我使用第一种方法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== '':
Run Code Online (Sandbox Code Playgroud)

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