import os
import pandas as pd
# 功能:遍历目录下的所有xls文件,合并到指定的一个文件
def main():
#指定目录
base = 'C:\\Users\\11578\\Desktop\\05'
desktop = os.path.join(os.path.expanduser("~"), 'Desktop')
#存放所有xls表的数据
allLineData = pd.DataFrame()
for excelFile in findAllFile(base):
# 读取工作簿和工作簿中的工作表
oneFileData =pd.read_excel(excelFile)
# append忽略行头(忽略第一行)
allLineData=allLineData.append(oneFileData, ignore_index=True)
# print(allLineData)
#写到桌面
writer=pd.ExcelWriter(os.path.join(desktop,'合并后的文件.xls'))
# 使用to_excel将之前读取的工作簿中工作表的数据写入到新建的工作簿的工作表中
allLineData.to_excel(writer, index=False)
# 保存并且关闭工作簿
writer.save()
#查找base目录下的所有xls和xlsx文件
def findAllFile(base):
for root, ds, fs in os.walk(base):
for f in fs:
if f.endswith('.xls') or f.endswith('.xlsx'):
fullname = os.path.join(root, f)
yield fullname
if __name__ == '__main__':
main()
gui版本
from tkinter import *
import os
import pandas as pd
def gui():
# 第1步,实例化object,建立窗口window
window=Tk()
# 第2步,给窗口的可视化起名字
window.title('Aggregation Excel')
window.geometry('530x150') # 这里的乘是小x
# 桌面
desktop=os.path.join(os.path.expanduser("~"), 'Desktop')
strvar=StringVar()
strvar.set(desktop)
l1=Label(window, text="扫描excel的目录")
e1=Entry(window, show=None, width=50)
l2=Label(window, text="合并后文件的存放路径")
e2=Entry(window, show=None, width=50, textvariable=strvar)
def insert_point(): # 在鼠标焦点处插入输入内容
# 扫描excel的目录路径
e1value=e1.get()
# 合并后存放的目录路径
e2value=e2.get()
# t.insert('insert', var)
aggExcel(e1value,e2value)
# 第6步,创建并放置两个按钮分别触发两种情况
btn1=Button(window, text='开始合并', width=10,
height=2, command=insert_point)
t=Text(window, height=3)
l1.grid(row=1, column=1, sticky=E)
e1.grid(row=1, column=2, sticky=E)
l2.grid(row=2, column=1, sticky=E)
e2.grid(row=2, column=2, sticky=E)
btn1.grid(row=4, column=1, sticky=E)
# 第8步,主窗口循环显示
window.mainloop()
def aggExcel(filedir,writePlace):
# 指定目录
# base='C:\\Users\\11578\\Desktop\\05'
# base = e1value
# 存放所有xls表的数据
allLineData=pd.DataFrame()
for excelFile in findAllFile(filedir):
# 读取工作簿和工作簿中的工作表
oneFileData=pd.read_excel(excelFile)
# append忽略行头(忽略第一行)
allLineData=allLineData.append(oneFileData, ignore_index=True)
# print(allLineData)
# 写到桌面
writer=pd.ExcelWriter(os.path.join(writePlace, '合并后的文件.xls'))
# 使用to_excel将之前读取的工作簿中工作表的数据写入到新建的工作簿的工作表中
allLineData.to_excel(writer, index=False)
# 保存并且关闭工作簿
writer.save()
#查找base目录下的所有xls和xlsx文件
def findAllFile(base):
for root, ds, fs in os.walk(base):
for f in fs:
if f.endswith('.xls') or f.endswith('.xlsx'):
fullname = os.path.join(root, f)
yield fullname
if __name__ == '__main__':
gui()
打包成exe:
打开文件所在的目录下:cmd执行命令
pyinstaller -w xxx.py
GUI参考:https://www.cnblogs.com/shwee/p/9427975.html
pandas参考:https://zhuanlan.zhihu.com/p/31541902
打包教程:https://blog.51cto.com/u_15284226/2988724