基于PySimpleGUI与Pandas的数据录入Excel工具开发问题求助
解决PySimpleGUI数据录入GUI的Excel整合问题
1. 自动生成列标题并关联用户输入
核心思路是将GUI输入项的key作为Excel列标题,提交时把输入数据整理成Pandas DataFrame,保存时判断文件是否存在:不存在则写入表头+数据,存在则追加数据(不重复写表头)。
2. 用Pandas实现新建/打开Excel的GUI交互
替换sg.FolderBrowse(),用sg.FileSaveAs()(新建/另存为)和sg.FileBrowse()(打开已有文件)获取文件路径,结合Pandas完成Excel读写。
完整可运行代码
import PySimpleGUI as sg import pandas as pd import os # 定义输入项,key直接对应Excel列标题 input_fields = [ ('First Name', sg.Input(key='First Name')), ('Last Name', sg.Input(key='Last Name')), ('Email', sg.Input(key='Email')) ] layout = [ [sg.Text('Excel数据录入工具')], [sg.Text('目标文件:'), sg.Input(key='file_path', readonly=True), sg.FileBrowse('打开', file_types=(('Excel文件', '*.xlsx'),)), sg.FileSaveAs('新建/另存为', file_types=(('Excel文件', '*.xlsx'),))], *[[sg.Text(label), input] for label, input in input_fields], [sg.Button('提交'), sg.Button('清空')], [sg.StatusBar('', key='status')] ] window = sg.Window('数据录入', layout) current_file = None while True: event, values = window.read() if event == sg.WIN_CLOSED: break elif event == '打开': current_file = values['file_path'] window['status'].update(f'已打开文件: {current_file}' if os.path.exists(current_file) else '文件不存在,请检查路径') elif event == '新建/另存为': current_file = values['file_path'] window['status'].update(f'已设置保存路径: {current_file}') elif event == '提交': if not current_file: window['status'].update('请先选择或新建Excel文件') continue # 整理输入数据,只保留输入项对应的列 df_new = pd.DataFrame([values])[[key for _, (_, key) in enumerate(input_fields)]] # 写入Excel if os.path.exists(current_file): # 追加模式,不重复写表头 with pd.ExcelWriter(current_file, mode='a', engine='openpyxl', if_sheet_exists='overlay') as writer: df_new.to_excel(writer, index=False, header=False, startrow=writer.sheets['Sheet1'].max_row) else: # 新建文件,写入表头 df_new.to_excel(current_file, index=False) window['status'].update(f'数据已保存到 {current_file}') elif event == '清空': for _, (_, key) in enumerate(input_fields): window[key].update('') window.close()
关键说明
- 输入项的
key直接映射为Excel列标题,无需手动定义表头 - 用
FileBrowse和FileSaveAs实现文件的打开与新建操作,替代文件夹选择 - 追加数据时使用
openpyxl引擎的if_sheet_exists='overlay'参数,避免覆盖原有数据 - 通过
os.path.exists判断文件状态,自动决定是否写入表头
内容的提问来源于stack exchange,提问作者jessica alison
相关产品推荐
相关产品推荐

