使用python调用资源管理器窗口选择需要合并的excel文件,实现合并所有选择excel文件中的sheet表,用所有文件的所有sheet表生成一个新的文件,新文件的路径及文件名称将在Windows资源管理器中输入;
效果
源码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127
| from tkinter import * from tkinter import filedialog from tkinter import messagebox from openpyxl import Workbook, load_workbook from copy import copy
class Application(Frame): def __init__(self, master=None): super().__init__(master) self.master = master self.master.title("Excel工作表合并") self.master.geometry("260x150") self.pack(expand=True, fill='both', padx=10, pady=10)
Label(self, text="说明:合并选中Excel文件的所有Sheet表;").pack(pady=5)
self.select_files_button = Button(self, text="选择文件", command=self.select_files) self.select_files_button.pack(side=LEFT, padx=5)
self.quit_button = Button(self, text="退出", command=self.master.destroy) self.quit_button.pack(side=RIGHT, padx=5)
Label(self, text="© 嗜血星空earth").pack(side=BOTTOM)
def select_files(self): self.files = filedialog.askopenfilenames()
def select_files(self): files = filedialog.askopenfilenames( title="选择需要合并的Excel文件", filetypes=[("Excel files", "*.xlsx;*.xls")], )
if not files: messagebox.showerror("错误", "没有选择任何文件!") return
new_wb = Workbook() new_wb.remove(new_wb.active)
for file in files: wb = load_workbook(file)
for ws in wb.worksheets: new_ws = new_wb.create_sheet(ws.title)
new_ws.sheet_properties.tabColor = ws.sheet_properties.tabColor new_ws.page_setup = copy(ws.page_setup) new_ws.print_options = copy(ws.print_options)
for row in ws.iter_rows(max_col=ws.max_column, max_row=ws.max_row): for cell in row: new_cell = new_ws.cell(row=cell.row, column=cell.column)
new_cell.value = cell.value
if cell.font: new_cell.font = copy(cell.font)
if cell.fill: new_cell.fill = copy(cell.fill)
if cell.border: new_cell.border = copy(cell.border)
if cell.number_format: new_cell.number_format = copy(cell.number_format)
if cell.protection: new_cell.protection = copy(cell.protection)
if cell.alignment: new_cell.alignment = copy(cell.alignment)
if cell.data_type == 'f': new_cell.value = cell.value new_cell.data_type = 'f' new_cell.number_format = cell.number_format
if cell.data_type == 'b': new_chart = copy(cell.chart) new_ws.add_chart(new_chart, new_cell.coordinate)
save_file = filedialog.asksaveasfilename( title="保存Excel文件", defaultextension=".xlsx", filetypes=[("Excel files", "*.xlsx")], )
if not save_file: messagebox.showerror("错误", "文件名不能为空!") return
new_wb.save(save_file)
new_wb.close()
messagebox.showinfo("提示", "文件已保存。")
root = Tk() app = Application(master=root) app.mainloop()
|
实例
封装
1
| pyinstaller -F --noconsole --hidden-import tkinter main.py
|