需要的Python库
- 【os】用于路径下文件名称获取
- 【time】用于输入时间进度等
- 【pandas】读取数据并处理汇总
- 【xlrd】pip install xlrd,读取Excel相关库pandas依赖
- 【openpyxl】pip install openpyxl,Excel相关库
导入相关包
import osimport timeimport pandas as pd
数据读取与汇总
pandas的Excel读取方法
pd.read_excel( io, sheet_name=0, header=0, names=None, index_col=None, usecols=None, squeeze=False, dtype=None, engine=None, converters=None, true_values=None, false_values=None, skiprows=None, nrows=None, na_values=None, keep_default_na=True, verbose=False, parse_dates=False, date_parser=None, thousands=None, comment=None, skipfooter=0, convert_float=True, mangle_dupe_cols=True, **kwds,)
编写函数实现目录文件循环读取
函数返回一个汇总数据的DataFrame
def 读取Excel(excel_path): read_time=time.time() print('{} 准备读取"{}"路径下的文件!'.format(time.strftime('%Y-%m-%d %H:%M:%S'),excel_path)) items=[item[2] for item in os.walk(excel_path)] files=items[0] print('{} 该路径下存在【{}】个文件!'.format(time.strftime('%Y-%m-%d %H:%M:%S'),len(files))) data=None print('{} 正在读取:{}'.format(time.strftime('%Y-%m-%d %H:%M:%S'),files[0])) n=None# 设置跳过读取的行数读取文件从第几行之后开始 data=pd.read_excel('{}/{}'.format(excel_path,files[0]), skiprows=n) for file in files[1:]: print('{} 正在读取:{}'.format(time.strftime('%Y-%m-%d %H:%M:%S'),file)) df=pd.read_excel('{}/{}'.format(excel_path,file), skiprows=n) data=pd.concat([data,df]) print('{} 数据读取完成,用时{:.2f}秒!'.format(time.strftime('%Y-%m-%d %H:%M:%S'),time.time()-read_time)) return data
汇总数据存储
pandas中DataFrame保存为Excel的方法
pd.read_excel( io, sheet_name=0, header=0, names=None, index_col=None, usecols=None, squeeze=False, dtype=None, engine=None, converters=None, true_values=None, false_values=None, skiprows=None, nrows=None, na_values=None, keep_default_na=True, verbose=False, parse_dates=False, date_parser=None, thousands=None, comment=None, skipfooter=0, convert_float=True, mangle_dupe_cols=True, **kwds,)
编写函数实现数据保存
def 存储Excel(path,name,data): # 函数传入参数为保存时文件路径,文件名,以及需要保存的数据(自定义读取函数返回结果) save_time=time.time() print('{} 正在保存数据,请耐心等待……!'.format(time.strftime('%Y-%m-%d %H:%M:%S'))) try: df=data df.to_excel('{}/{}'.format(path,name)) print('{} 数据已保存至:"{}/{}"!'.format(time.strftime('%Y-%m-%d %H:%M:%S'),path,name)) except BaseException as e: print('{} 数据保存失败 错误信息为:{}'.format(time.strftime('%Y-%m-%d %H:%M:%S'),e)) print('{} 数据存储完毕,用时{:.2f}秒!'.format(time.strftime('%Y-%m-%d %H:%M:%S'),time.time()-save_time))
程序封装与全代码
import osimport timeimport pandas as pd# pip install xlrd# pip install openpyxlclass Excel操作: def 读取Excel(self,excel_path): read_time=time.time() print('{} 准备读取"{}"路径下的文件!'.format(time.strftime('%Y-%m-%d %H:%M:%S'),excel_path)) items=[item[2] for item in os.walk(excel_path)] files=items[0] print('{} 该路径下存在【{}】个文件!'.format(time.strftime('%Y-%m-%d %H:%M:%S'),len(files))) data=None print('{} 正在读取:{}'.format(time.strftime('%Y-%m-%d %H:%M:%S'),files[0])) n=None# 设置跳过读取的行数读取文件从第几行之后开始 data=pd.read_excel('{}/{}'.format(excel_path,files[0]), skiprows=n) for file in files[1:]: print('{} 正在读取:{}'.format(time.strftime('%Y-%m-%d %H:%M:%S'),file)) df=pd.read_excel('{}/{}'.format(excel_path,file), skiprows=n) data=pd.concat([data,df]) print('{} 数据读取完成,用时{:.2f}秒!'.format(time.strftime('%Y-%m-%d %H:%M:%S'),time.time()-read_time)) return data def 存储Excel(self,path,name,data): save_time=time.time() print('{} 正在保存数据,请耐心等待……!'.format(time.strftime('%Y-%m-%d %H:%M:%S'))) try: df=data df.to_excel('{}/{}'.format(path,name)) print('{} 数据已保存至:"{}/{}"!'.format(time.strftime('%Y-%m-%d %H:%M:%S'),path,name)) except BaseException as e: print('{} 数据保存失败 错误信息为:{}'.format(time.strftime('%Y-%m-%d %H:%M:%S'),e)) print('{} 数据存储完毕,用时{:.2f}秒!'.format(time.strftime('%Y-%m-%d %H:%M:%S'),time.time()-save_time)) def 运行(self,excel_path,path,name): ''' Parameters ---------- excel_path : TYPE 读取数据目录. path : TYPE 保存数据路径. name : TYPE 保存数据文件名(xxx.xlsx). Returns ------- None. ''' start_time=time.time() data=self.读取Excel(excel_path) self.存储Excel(path, name, data) print('{} 程序运行结束,用时{:.2f}秒!'.format(time.strftime('%Y-%m-%d %H:%M:%S'),time.time()-start_time)) if __name__=='__main__': Excel=Excel操作() # 运行参数设置 excel_path='' path='' name='汇总输出.xlsx' Excel.运行(excel_path,path,name)
运行演示
![eaf80eea16718a24dd6c393ef2cea1f1.png](https://i-blog.csdnimg.cn/blog_migrate/736a7cb0aa7d0ff1c225e8f6955dfb12.jpeg)
运行界面