import tkinter as tkfrom tkinter import ttk, filedialog, messageboximport pandas as pdimport osclass SocialSecurityApp: def __init__(self, root): self.root = root self.root.title("社保年度申报汇总工具") self.root.geometry("600x400+600+300") # 存储选择的文件路径 self.selected_files = [] self.setup_ui() def setup_ui(self): """构建简单的交互界面""" tk.Label(self.root, text="第一步:选择全年社保汇总表", font=("Arial", 12)).pack(pady=10) self.btn_select = tk.Button(self.root, text="选择 Excel 文件", command=self.select_files, bg="#2196F3", fg="white") self.btn_select.pack(pady=5) self.files_list = tk.Listbox(self.root, height=10, width=70) self.files_list.pack(padx=10, pady=5) self.btn_run = tk.Button(self.root, text="开始计算并导出", command=self.process_data, bg="#4CAF50", fg="white") self.btn_run.pack(pady=10) def select_files(self): """文件选择对话框""" files = filedialog.askopenfilenames(filetypes=[("Excel Files", "*.xlsx *.xls")]) if files: self.selected_files = list(files) self.files_list.delete(0, tk.END) for f in files: self.files_list.insert(tk.END, os.path.basename(f)) def process_data(self): """核心处理逻辑""" if not self.selected_files: messagebox.showwarning("提示", "请先选择文件!") return try: # 1. 批量读取并合并所有月份的数据 # 假设第7行开始是数据,所以 skiprows=6 dfs = [pd.read_excel(f, skiprows=6) for f in self.selected_files] df_all = pd.concat(dfs, ignore_index=True) # 2. 定义列索引(根据税务局导出的标准表结构) # 索引 4 是品目,6 是基数,8 是金额 cat_col, base_col, amt_col = df_all.columns[4], df_all.columns[6], df_all.columns[8] # 3. 汇总计算 summary_df = ( df_all.dropna(subset=[cat_col]) # 剔除空行 .groupby(cat_col) # 按征收品目分组 .agg({base_col: 'sum', amt_col: 'sum'}) # 同时对基数和金额求和 .reset_index() # 恢复成标准的表格格式 .assign( # 批量转换单位为「万元」 缴费基数总额=lambda x: (x[base_col] / 10000).map("{:.5f}万".format), 应缴金额=lambda x: (x[amt_col] / 10000).map("{:.5f}万".format) ) ) # 4. 导出到桌面 desktop = os.path.join(os.path.expanduser("~"), "Desktop") output_path = os.path.join(desktop, "年度社保申报汇总表.xlsx") summary_df.to_excel(output_path, index=False) messagebox.showinfo("成功", f"汇总完成!文件已保存在桌面:\n{output_path}") os.startfile(output_path) # 处理完直接打开文件 except Exception as e: messagebox.showerror("错误", f"处理过程中发生异常:{e}")if __name__ == "__main__": root = tk.Tk() app = SocialSecurityApp(root) root.mainloop()