如何在PySimpleGUI的Word模板生成器中支持多模板选择?
实现多Word模板批量生成功能的解决方案
要实现多模板选择并批量生成文档,需要从GUI布局调整、参数传递修正、多模板遍历逻辑三个方面修改代码,以下是完整的实现方案:
import PySimpleGUI as sg import pandas as pd from docxtpl import DocxTemplate from pathlib import Path # ----------Instructions for use function----------- # def instructions(): sg.popup_scrolled(f"HOW TO USE THE TEMPLATE GENERATOR " f"\n 1. Store the application and supporting folder directly on the Desktop. Otherwise, the program won’t work." f"\n 2. Populate the raw_data.xlsx with all relevant details you need, e.g. Legal entity name, address, VATid, Base and click charges, etc." f"\n 3. Once you start the program, select one or more Word templates in the 'Import Word Template:' field." f"\n 4. Then select raw_data.xlsx in the 'Import Excel raw data:' field." f"\n 5. Click on 'Populate Template' ") # ----------Main program function for creating multiple templates----------- # def generate_word_template(word_template_paths, excel_path, output_dir): # 使用传入的参数,移除硬编码路径 output_dir = Path(output_dir) output_dir.mkdir(exist_ok=True) df = pd.read_excel(excel_path, sheet_name="Sheet3") records = df.to_dict(orient="records") # 遍历每个选中的Word模板 for template_path in word_template_paths: template_name = Path(template_path).stem # 获取模板文件名(不含后缀) for record in records: doc = DocxTemplate(template_path) doc.render(record) # 生成带模板标识的输出文件名,避免重名 output_path = output_dir / f"{record['SITECODE']}-{template_name}_HP Advance_CO.docx" doc.save(output_path) sg.popup_no_titlebar("All templates generated! :)") # ----------GUI Definition. Program Window view----------- # layout =[ [sg.Text("Import Word Template(s):"), sg.Input(key="-WORD_TEMPLATES-"), sg.FileBrowse(file_types=(('Word Template', '*.doc*'),), multiple=True)], [sg.Text("Import Excel raw data:"), sg.Input(key="-EXCEL_PATH-"), sg.FileBrowse(file_types=(('Excel raw data', '*.xls*'),))], [sg.Text("Output Folder:"), sg.Input(key="-OUT_DIR-"), sg.FolderBrowse()], [sg.Exit(), sg.Button("Populate Template"), sg.Button("Instructions")], ] window = sg.Window("Populate multiple Word templates", layout) # ----------Closing program and displaying error message----------- # while True: event, values = window.read() if event in (sg.WINDOW_CLOSED, "Exit"): break if event == "Instructions": instructions() if event == "Populate Template": # 获取多选的模板路径,PySimpleGUI会用分号分隔多个路径 word_template_paths = values["-WORD_TEMPLATES-"].split(";") # 过滤可能的空路径(如果用户没选文件) word_template_paths = [path.strip() for path in word_template_paths if path.strip()] if not word_template_paths: sg.popup_error("Please select at least one Word template!") continue if not values["-EXCEL_PATH-"]: sg.popup_error("Please select Excel raw data file!") continue if not values["-OUT_DIR-"]: sg.popup_error("Please select output folder!") continue generate_word_template( word_template_paths=word_template_paths, excel_path=values["-EXCEL_PATH-"], output_dir=values["-OUT_DIR-"] ) window.close()
关键修改说明
- 多模板选择支持:
- 为Word模板的
FileBrowse组件添加multiple=True参数,允许用户一次性选中多个.doc/.docx文件 - 用
-WORD_TEMPLATES-作为输入框的唯一Key,避免与Excel输入框的Key冲突
- 为Word模板的
- 核心逻辑优化:
- 修改
generate_word_template函数的第一个参数为word_template_paths(列表类型),遍历每个模板文件生成对应文档 - 移除函数内硬编码的路径,完全使用用户选择的路径参数
- 输出文件名加入模板名称标识,避免不同模板生成的文件重名
- 修改
- 参数校验增强:
- 在点击生成按钮时,检查模板、Excel文件、输出路径是否已选择,避免空参数导致的错误
- 细节修正:
- 修正说明文本中的拼写错误(
Ones改为Once) - 为输出文件添加
.docx后缀,确保生成的文件可直接用Word打开
- 修正说明文本中的拼写错误(
内容的提问来源于stack exchange,提问作者Manedon
相关产品推荐
相关产品推荐

