我正在构建一个 Word 模板生成器,用于使用 excel 数据创建批量文档的工作。 但是我现在只能选择 1 个模板,我希望能够使用多个模板。 我可以写一个 if 语句来改变我的 word_template_path 但是当我试图将这段代码嵌入到 pysimpleGUI 时我不知道该怎么做。
# ----------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. Ones you start the program, select test_template.docx in the Input File: field."
f"\n 4. Then select raw_data.xlsx in the Excel Files: field."
f"\n 5. Click on Generate Template ")
# ----------Main program function for creating multiple templates----------- #
def generate_word_template(word_template_path, excel_path, output_path):
base_dir = Path.home() / "Desktop"
word_template_path = base_dir / "test_template.docx"
excel_path = base_dir / "data2.xlsx"
output_dir = base_dir / "OUTPUT"
output_dir.mkdir(exist_ok=True)
df = pd.read_excel(excel_path, sheet_name="Sheet3")
for record in df.to_dict(orient="records"):
doc = DocxTemplate(word_template_path)
doc.render(record)
output_path = output_dir / f"{record['SITECODE']}-HP Advance_CO"
doc.save(output_path)
sg.popup_no_titlebar("Done! :)")
# ----------GUI Definition. Program Window view----------- #
layout =[
[sg.Text("Import Word Template:"), sg.Input(key="-IN-"), sg.FileBrowse(file_types=(("Word Template", "*.doc*"),))],
[sg.Text("Import Excel raw data:"), sg.Input(key="-IN-"), sg.FileBrowse(file_types=(("Excel raw data", "*.xls*"),))],
[sg.Text("Output Folder:"), sg.Input(key="-OUT-"), 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":
generate_word_template(
word_template_path=values["-IN-"],
excel_path=values["-IN-"],
output_path=values["-OUT-"]
)
window.close()