Excel合并小工具编写

Excel合并小工具编写

由于女朋友太懒,又要让我干活,所以写一个简单的Excel合并小工具来帮她合并一下Excel。

待合并excel

需求分析

由于从数据库导出来的数据过大,所以默认被分成了多个Sheet,现在的需要「将他们合并在一起进行数据透视操作」。

使用到的库

1
2
3
4
import os
import threading
from tkinter import *
import pandas as pd
  1. os:文件操作,方便进行文件名的修改等操作
  2. threading:线程模块,可以方便进行多线程操作
  3. tkinter:python自带的GUI界面
  4. pandas:Excel数据处理的主力

还用到了pyinstaller来进行打包,方便后续使用

合并流程

合并可以分为:

  • 读取Excel各Sheet内容
  • 进行组合
  • 写入新的Excel中

读取

入参为pathname,方便动态调整

1
2
3
def get_df(path, name):
df = pd.DataFrame(pd.read_excel(path, sheet_name=name))
return df

合并

由于怕合并少了,所以计算一下每个Sheet中内容条数合并后的内容条数

1
2
3
4
5
6
7
8
def concat_df(df_list):
sum = 0
for i in df_list:
sum += len(i)
print(len(i))
result = pd.concat(df_list, sort=False)
print(f'理论上合并后条数为{sum},实际为{len(result)}')
return result

写入

1
2
3
4
def write_into_xls(result, file_name='result.xls'):
writer = pd.ExcelWriter(file_name)
result.to_excel(writer, index=False)
writer.save()

流程组合

通过os模块裁剪传入的excel文件路径,进行拆分重组

1
2
3
p, name = os.path.split(file_path)
_, n = os.path.splitext(file_path)
new_path = os.path.join(p, f'(合并后){name.replace(n, ".xlsx")}')
1
2
3
4
5
import os
os.path.splitext('/Users/zhongxin/PycharmProjects/datawork/ZB-ECRC业务线路查询 3.10浙皖.xls')
Out[3]: ('/Users/zhongxin/PycharmProjects/datawork/ZB-ECRC业务线路查询 3.10浙皖', '.xls')
os.path.split('/Users/zhongxin/PycharmProjects/datawork/ZB-ECRC业务线路查询 3.10浙皖.xls')
Out[4]: ('/Users/zhongxin/PycharmProjects/datawork', 'ZB-ECRC业务线路查询 3.10浙皖.xls')

讲上述流程进行组合

1
2
3
4
5
6
7
8
9
10
11
def work():
file_path = path.get()
sheet_list = sheet.get().split('|')
df_list = []
p, name = os.path.split(file_path)
_, n = os.path.splitext(file_path)
new_path = os.path.join(p, f'(合并后){name.replace(n, ".xlsx")}')
for i in sheet_list:
df_list.append(get_df(file_path, i))
result = concat_df(df_list)
write_into_xls(result, new_path)

使用TK编写简单的GUI界面

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
top = Tk()
top.title('Excel合并工具')
top.geometry('600x400')
frame = Frame(top)
frame.pack()
lab = Label(frame, text='待合并Excel路径: ')
lab.grid(row=0, column=0, sticky=W)
path = Entry(frame)
path.insert(0, '/Users/zhongxin/PycharmProjects/datawork/ZB-ECRC分销出货查询 4.10-4.11浙皖.xls')
path.grid(row=0, column=1, sticky=W)

lab = Label(frame, text='子sheet名称(使用|分割): ')
lab.grid(row=1, column=0, sticky=W)
sheet = Entry(frame)
sheet.insert(0, '分销明细|分销明细_1')
sheet.grid(row=1, column=1, sticky=W)

btn1 = Button(frame, text="开始合并", command=lambda: thread_it(work), width=20)
btn1.grid(row=1, column=2, sticky=W)

text = Text(top, width=20, height=100)
text.pack(fill=X, side=BOTTOM)
top.mainloop()

GUI界面

github路径

https://github.com/zx490336534/ExcelConcat

 wechat
欢迎您扫一扫上面的微信公众号,订阅我的博客!
您的支持将鼓励我继续创作!