Python实现多个Sheet文件合并(传参)
用法:传入需要遍历的来源目录路径和结果文件路径
import os
import pandas as pd
class Data_Merge:
def __init__(self,source_dire,result_file):
self.source_dire=source_dire
self.result_file=result_file
def table_merge(self):
dir_or_files = os.walk(self.source_dire)
for path, dir_list, file_list in dir_or_files:
for file_name in file_list:
# 文件名转小写,文件结尾必须是'xls'
if str(file_name).lower().endswith('xls'):
file_path = os.path.join(path, file_name)
df = pd.ExcelFile(file_path)
sheet_names = df.sheet_names
for sheet_name in sheet_names:
df_row = pd.read_excel(file_path, sheet_name=sheet_name)
csv_file_path = f'{self.result_file}{sheet_name}.csv'
df_row.to_csv(csv_file_path, mode='a', index=False,header=(not os.path.exists(csv_file_path)))
if __name__ == "__main__":
Data_Merge('./data','./result/').table_merge()
调用
from test.table_merge_fun import Data_Merge
Data_Merge('./data', './result/').table_merge()
reference
107.定义Python中的类
https://www.bilibili.com/video/BV1wD4y1o7AS?p=108