Python脚本拆分Excel中空行分隔多表的问题排查求助
Python脚本拆分Excel中空行分隔多表的问题排查求助
大家好,我现在碰到一个Excel表格拆分的问题,想请各位帮忙看看我的Python脚本哪里出了问题,或者有没有优化的空间。
我的场景
我有一个名为Sec_10.xlsx的Excel工作簿,其中一张名为Sheet的工作表里,有多个结构完全相同的小表格——每个小表格都是Column A和Column B作为表头,下面跟着两行数据,然后用整行空白分隔开,结构大概是这样的:
Column A | Column B
Cell 1 | Cell 2
Cell 3 | Cell 4
---(整行空白)---
Column A | Column B
Cell 1 | Cell 2
Cell 3 | Cell 4
---(整行空白)---
...(重复N次)
我写的代码
为了把这些小表格拆成单独的Pandas DataFrame(方便后续导出成CSV或独立Excel工作表),我查了不少资料(谷歌、ChatGPT、Anaconda相关文档),写了如下脚本:
import pandas as pd def separate_excel_tables(excel_file_path, sheet_name="Sheet"): """ Separates tables from an Excel sheet where tables are separated by blank rows. Args: excel_file_path: Path to the target Excel file (e.g., Sec_10.xlsx) sheet_name: Name of the worksheet to process Returns: list: A list of pandas DataFrames, each representing a separated table. """ # Read the entire worksheet into a DataFrame df = pd.read_excel(excel_file_path, sheet_name=sheet_name, header=0) # Find all indices of fully blank rows blank_row_indices = df[df.isnull().all(axis=1)].index.tolist() # Add boundary indices to handle first and last tables table_boundaries = [-1] + blank_row_indices + [len(df)] separated_tables = [] # Iterate through boundaries to split the DataFrame for i in range(len(table_boundaries) - 1): start_row = table_boundaries[i] + 1 end_row = table_boundaries[i + 1] # Extract the potential table segment potential_table = df.iloc[start_row:end_row] # Skip if the segment is empty if not potential_table.empty: # Assume first row of the segment is the header header_row = potential_table.iloc[0] data_rows = potential_table.iloc[1:] # Create DataFrame with correct header table_df = pd.DataFrame(data_rows.values, columns=header_row.values) # Remove any remaining fully blank rows inside the table table_df = table_df.dropna(how='all') # Only add non-empty tables to the result list if not table_df.empty: separated_tables.append(table_df) return separated_tables # Example usage (commented out) # excel_file = 'Sec_10.xlsx' # tables = separate_excel_tables(excel_file) # # Loop through the list to export each table # for idx, table in enumerate(tables): # print(f"Table {idx+1}:\n{table}\n") # # Example export to CSV # # table.to_csv(f"table_{idx+1}.csv", index=False)
我的预期与疑问
我预期这段代码能返回一个DataFrame列表,每个DataFrame对应一个拆分出来的独立小表格,之后我可以循环遍历这个列表,把每个表格导出成CSV或者单独的Excel工作表。但实际运行后,要么拆分出来的表格表头有问题,要么存在冗余的空行,甚至可能漏拆了部分表格。
想请各位帮忙排查下脚本里的逻辑问题,或者有没有更可靠的方法来实现这个需求?
内容来源于stack exchange
相关产品推荐
相关产品推荐

