项目概况

Excel文件拆分

2026-01-291 min read数据处理
excel

Excel文件拆分

python
1import pandas as pd 2import os 3 4def split_excel_to_csv(file_path, rows_per_file=20000): 5 # 读取Excel文件 6 df = pd.read_excel(file_path) 7 8 # 获取首行 9 header = df.columns.to_frame().T # 保持首行作为 DataFrame 10 11 print(header) 12 13 # 将数据按20000行拆分 14 for i in range(0, len(df), rows_per_file): 15 # 创建小表格 16 chunk = df.iloc[i:i + rows_per_file] 17 18 # 组合成新的DataFrame,保持首行不变 19 new_df = pd.concat([header, chunk], ignore_index=True) 20 21 # 生成新的文件名 22 base_name, _ = os.path.splitext(file_path) 23 file_name = os.path.basename(file_path).split('.xlsx')[0] 24 file_name = f"{file_name}-{i // rows_per_file + 1}.csv" 25 dir_name = os.path.dirname(file_path); 26 new_file_name = dir_name + '/新建文件夹/' + file_name 27 # 保存为CSV格式 28 new_df.to_csv(new_file_name, index=False, header=False) # header=False因为首行已包含在数据中 29 30 print(f"拆分完成,共生成 {len(df) // rows_per_file + 1} 个文件。") 31 32dir_path = '/Users/xxx/PycharmProjects/drissionpagedocs/MasterData' 33 34for i in os.listdir(dir_path): 35 if (i.endswith(".xlsx")): 36 file_path = dir_path + '/' + i; 37 print(file_path) 38 split_excel_to_csv(file_path, 39 rows_per_file=2)