百木园-与人分享,
就是让自己快乐。

Python-目录下相同格式的Excel文件合并

最近在客户现场接到一个任务,需要将全国所有省份的数据进行合并。目录是分层级的,首先是省份目录、然后地级市目录、最里面是区县目录。需要将每个目录中的数据进行合并,然后添加4列数据,并将某一个列的数据进行拆分和处理。总共将近3000张个Excel文件需要处理,如果手工处理的话,估计要搞一个星期才能搞完。为了在规定时间内完成任务,我通过编写python程序实现了这样的功能。这里我简单分享下单个目录中Excel文件合并的模块。

 

 

Python代码:#!/usr/bin/env python# coding:utf-8 \"\"\"@File Name: zwc002.py@Version: 1.0@Python Version: 3.7@Author: liguanbin@Created Time: 2021/5/21 9:04@Software: PyCharm@Desc:\"\"\"import osimport xlrdimport xlsxwriterimport glob# 获取要合并的所有excel表格def get_excel(): global file_path global current_folder global new_excel_path file_path = input(\"请输入Excel文件所在的目录:\") if not file_path.endswith(\'\\\\\'): current_folder = os.path.basename(file_path) file_path = file_path + \"\\\\\" else: current_folder = os.path.basename(os.path.dirname(file_path)) new_excel=current_folder + \"_合并结果.xlsx\" new_excel_path = os.path.join(file_path,new_excel) # 新建的exce文件绝对路径 if os.path.isfile(new_excel_path): os.remove(new_excel_path) # 如果文件已经存在就删除,避免重复执行插入重复 all_excel = glob.glob(file_path + \"*.xlsx\") print(\"该目录下有\" + str(len(all_excel)) + \"个Excel文件:\") if (len(all_excel) == 0): return 0 else: for i in range(len(all_excel)): print(all_excel[i]) return all_excel# 获取sheet下的数据def get_sheet_data(sheet): row = sheet.nrows for i in range(row): if (i == 0): global biao_tou biao_tou = sheet.row_values(i) continue values = sheet.row_values(i) all_data1.append(values) return all_data1if __name__ == \'__main__\': all_excel = get_excel() # 得到要合并的所有exce表格数据 if (all_excel == 0): print(\"该目录下无.xlsx文件!请检查您输入的目录是否有误!\") exit() all_data1 = [] # 用于保存合并的所有行的数据 # 下面开始文件数据的获取 for excel in all_excel: fh = xlrd.open_workbook(excel) # 打开文件 sheets = fh.sheets() # 获取文件下的所有sheet for sheet_index in range(len(sheets)): all_data1 = get_sheet_data(sheets[sheet_index]) # 获取一个sheet下的所有行的数据,追加到数组中 all_data1.insert(0, biao_tou) # 表头写入(只需要写入一个) fh1 = xlsxwriter.Workbook(new_excel_path) # 新建一个excel表 title_formater=fh1.add_format({\'border\': 1,\'bold\':True,\'align\':\'center\',\'bg_color\':\'3399FF\',\'font_size\':12}) # 标题格式:边框:1、加粗、居中、填充:蓝色、字体:12 common_formater = fh1.add_format({\'border\': 1}) # 数据格式:边框:1 new_sheet_name=\"执常委列表\" # 指定sheet的名称 new_sheet = fh1.add_worksheet(new_sheet_name) # 新建一个sheet for i in range(len(all_data1)): for j in range(len(all_data1[i])): c = all_data1[i][j] if i==0: new_sheet.write(i, j, c, title_formater) else: new_sheet.write(i, j, c,common_formater) fh1.close() # 关闭该exce表 print(\"\\033[1;34m文件合并成功,请查看\" + new_excel_path + \"\\033[0m\")效果演示:

 

 合并后的文件:

 

来源:https://www.cnblogs.com/yeyuzhuanjia/p/14818913.html
图文来源于网络,如有侵权请联系删除。

未经允许不得转载:百木园 » Python-目录下相同格式的Excel文件合并

相关推荐

  • 暂无文章