如何用Python合并多个Excel文件并跳过仅含表头的空工作簿?
解决CSV合并时跳过仅含表头文件的问题
核心思路
要跳过仅含表头的空文件,关键是判断文件中除表头外是否存在实际数据行。以下提供两种适配你需求的解决方案:一种基于你原有的xlwings代码改造,另一种用pandas实现更高效的合并。
方案一:基于xlwings改造原有代码
保留你原有的工具链,加入数据行判断逻辑:
from pathlib import Path import time import xlwings as xw SOURCE_DIR = "[你的文件夹路径]" # 替换为实际文件夹路径 excel_files = list(Path(SOURCE_DIR).glob('*.csv')) combined_wb = xw.Book() timestamp = time.strftime('%Y-%m-%d', time.localtime()) for excel_file in excel_files: wb = xw.Book(excel_file) sheet = wb.sheets[0] # CSV文件默认仅一个工作表 # 获取已用区域总行数,表头占1行,行数>1说明有数据 used_row_count = sheet.used_range.rows.count # 仅当存在实际数据时才复制工作表 if used_row_count > 1: sheet.api.Copy(After=combined_wb.sheets[0].api) wb.close() # 保存合并后的文件 combined_wb.save(f"{SOURCE_DIR}dailychecks_{timestamp}.xlsx") # 清理Excel进程 if len(combined_wb.app.books) == 1: combined_wb.app.quit() else: combined_wb.close()
进阶判断(处理表头后全是空行的情况)
如果部分文件表头后只有空行,可加入更严格的非空值检查:
# 替换原有的if判断部分 data_range = sheet.range(f"A2:{sheet.used_range.address.split('$')[-1]}") # 检查数据区域是否存在非空内容 has_valid_data = any(cell.value is not None and str(cell.value).strip() != "" for cell in data_range) if has_valid_data: sheet.api.Copy(After=combined_wb.sheets[0].api)
方案二:用pandas实现高效合并
pandas处理CSV文件的速度远快于xlwings,适合你每天数百次文件的场景:
from pathlib import Path import time import pandas as pd SOURCE_DIR = "[你的文件夹路径]" excel_files = list(Path(SOURCE_DIR).glob('*.csv')) combined_data = [] timestamp = time.strftime('%Y-%m-%d', time.localtime()) for excel_file in excel_files: df = pd.read_csv(excel_file) # 仅当DataFrame有数据行时才加入合并列表 if len(df) > 0: combined_data.append(df) # 合并所有数据并保存为Excel final_data = pd.concat(combined_data, ignore_index=True) final_data.to_excel(f"{SOURCE_DIR}dailychecks_{timestamp}.xlsx", index=False)
内容的提问来源于stack exchange,提问作者suitablewriter
相关产品推荐
相关产品推荐

