如何用openpyxl仅解析工作簿特定工作表或忽略空工作表?
没问题,我来帮你搞定这个openpyxl的问题~先说说你代码里的两个小错误:一是Python里布尔值要写小写的True,不是TRUE;二是get_sheet_by_name()这个方法只能接受单个工作表名称,不能传列表或者多个参数,这就是你报错的根源。
下面给你两种解决方案,第二种更贴合你「忽略空工作表」的核心需求:
方案一:指定访问特定工作表
现在openpyxl更推荐用wb[sheet_name]的方式获取工作表(get_sheet_by_name()已经被标记为弃用),我们可以遍历目标名称列表逐个处理,还能加个存在性判断避免报错:
import openpyxl # 修正布尔值大小写 wb = openpyxl.load_workbook("source_file.xlsx", data_only=True) target_sheets = ['Sheet1', 'Sheet2', 'Sheet4', 'Sheet5'] for sheet_name in target_sheets: if sheet_name in wb.sheetnames: ws = wb[sheet_name] # 执行你的解析操作,推荐用iter_rows提升效率 for row in ws.iter_rows(values_only=True): <do the necessary parsing operations here> else: print(f"工作表 {sheet_name} 不存在,自动跳过")
方案二:自动忽略所有空工作表(更优)
既然你的核心需求是忽略空工作表,那直接在加载工作簿后自动筛选非空表就好,不用先手动收集名称。这里提供两种判断空表的方式:
方式1:精准判断(检查是否有非空单元格)
适合工作表可能存在格式设置但无数据的场景,准确性更高:
import openpyxl wb = openpyxl.load_workbook("source_file.xlsx", data_only=True) # 筛选出所有有数据的工作表 non_empty_sheets = [] for ws in wb.worksheets: # 遍历所有单元格,判断是否存在非空值 has_data = any(cell.value is not None for row in ws.iter_rows() for cell in row) if has_data: non_empty_sheets.append(ws) # 处理非空工作表 for ws in non_empty_sheets: print(f"正在处理工作表:{ws.title}") for row in ws.iter_rows(values_only=True): <do the necessary parsing operations here>
方式2:快速判断(检查最大行/列)
适合没有额外格式设置的空表,执行速度更快:
import openpyxl wb = openpyxl.load_workbook("source_file.xlsx", data_only=True) # 通过最大行/列判断,空表通常max_row和max_column都为1 non_empty_sheets = [ws for ws in wb.worksheets if ws.max_row > 1 or ws.max_column > 1] for ws in non_empty_sheets: print(f"正在处理工作表:{ws.title}") for row in ws.iter_rows(values_only=True): <do the necessary parsing operations here>
内容的提问来源于stack exchange,提问作者LearneR
相关产品推荐
相关产品推荐

