实战案例:用Trae开发一个Word文档合并工具
需求分析:
帮我生成一个word文档合并工具,功能要求如下:
1.使用python语言;
2.将当前目录下的所有docx格式的文档合并成一个word文档,并在每个文档内容之前插入原文件名;
3.文件名被添加到每个文档内容之前,并设置为粗体和较大字号以便区分;
4.源文档中的表格也要合并进来,显示表格样式和边框,所有表格虚框改为表格实框;
5.原文档的纸张方向,转换合并后保持纸张方向不变。
6.在每个文档内容结尾处插入分页符
使用deepseek编写初始指令:
使用python-docx库创建Word文档合并工具,需实现以下功能:
1. 目录遍历与筛选
- 扫描当前目录下所有.docx文件
- 按文件名排序处理源文件
2. 独立分页与页面方向保持
- 检测第一个源文档的页面方向,继承该源文档的页面方向(横向/纵向)
- 在每个文档结尾,为下一个待合并文件创建独立分页来隔离不同文档的版式
- 检测每个源文档的页面方向,并继承源文档的页面方向(横向/纵向)
3.文件名插入与格式设置:
- 在每个新文件内容前插入文件名段落
- 设置文字格式为加粗+16号字体
4. 内容合并与格式保留
- 深度复制源文档XML元素
- 保留原始文字、段落、表格、图片等各元素的前后排序
- 保留原始段落/表格格式
5. 表格样式增强
- 保持单元格原有边框样式
- 保持单元格原有对齐方式
最终生成合并文档应保持:
- 各源文件独立分页
- 继承源文档的页面方向(横向/纵向)
- 各源文件的文件头部插入源文件的文件名
- 原始排版样式完整
- 表格边框样式统一
生成的程序名为"merge_docx.py",代码如下:
- import os
- import copy
- from docx import Document
- from docx.enum.section import WD_ORIENT
- from docx.oxml.shared import qn
- from docx.shared import Pt
- from tqdm import tqdm
- def merge_docx_files():
- # 文件扫描与筛选
- all_files = [f for f in os.listdir('.') if f.endswith('.docx')]
- source_files = [f for f in all_files if not f.lower().startswith('merged')]
- source_files.sort()
- if not source_files:
- print("未找到可合并的Word文档")
- return
- # 初始化目标文档
- # 获取首文件页面方向
- first_doc = Document(source_files[0])
- first_section = first_doc.sections[0]
-
- # 根据首文件初始化目标文档
- merged_doc = Document()
- initial_section = merged_doc.sections[0]
- initial_section.orientation = first_section.orientation
- initial_section.page_width = first_section.page_width
- initial_section.page_height = first_section.page_height
- initial_orientation = initial_section.orientation
- # 创建进度条
- progress = tqdm(source_files, desc="正在合并文档")
- # 内容合并处理
- for i, filename in enumerate(progress):
- src_doc = Document(filename)
-
- # 跳过空文档
- if not src_doc.paragraphs and not src_doc.tables:
- progress.write(f"跳过空文档: {filename}")
- continue
-
- # 添加文件名标题(首文件不加分页符)
- if i > 0:
- merged_doc.add_page_break()
-
- # 插入带格式的文件名段落
- para = merged_doc.add_paragraph(filename)
- para.style.font.bold = True
- para.style.font.size = Pt(16)
-
- # 创建新分节并设置方向
- new_section = merged_doc.add_section()
- if src_doc.sections[0].orientation != initial_orientation:
- new_section.orientation = src_doc.sections[0].orientation
- new_section.page_width = src_doc.sections[0].page_width
- new_section.page_height = src_doc.sections[0].page_height
-
- # 将文件名段落移动到新分节
- merged_doc.element.body[-2].addprevious(para._p)
-
- # 深度复制段落和表格到新分节
- for element in src_doc.element.body:
- if element.tag.endswith('sectPr'):
- continue
- new_element = copy.deepcopy(element)
- new_section._sectPr.addprevious(new_element)
-
- # 释放内存
- src_doc.save(filename)
- del src_doc
-
- # 保存最终文档
- merged_doc.save('merged.docx')
-
- if __name__ == "__main__":
- merge_docx_files()
- print("文档合并完成,结果保存为merged.docx")
复制代码
又改成了图形界面,代码为:
- import os
- import copy
- from docx import Document
- from docx.enum.section import WD_ORIENT
- from docx.oxml.shared import qn
- from docx.shared import Pt
- import tkinter as tk
- from tkinter import ttk, filedialog, messagebox # 新增ttk导入
- import threading
- selected_folder = None # 全局变量保存选择的文件夹路径
- def merge_docx_files():
- if not selected_folder:
- return
-
- os.chdir(selected_folder)
- # 文件扫描与筛选
- all_files = [f for f in os.listdir('.') if f.endswith('.docx')]
- source_files = [f for f in all_files if not f.lower().startswith('merged')]
- source_files.sort()
- if not source_files:
- messagebox.showinfo("提示", "未找到可合并的Word文档")
- create_gui.merge_button.config(state=tk.NORMAL) # 恢复按钮状态
- return
- # 初始化目标文档
- first_doc = Document(source_files[0])
- first_section = first_doc.sections[0]
-
- merged_doc = Document()
- initial_section = merged_doc.sections[0]
- initial_section.orientation = first_section.orientation
- initial_section.page_width = first_section.page_width
- initial_section.page_height = first_section.page_height
- initial_orientation = initial_section.orientation
- total_files = len(source_files)
- for i, filename in enumerate(source_files):
- src_doc = Document(filename)
-
- # 跳过空文档
- if not src_doc.paragraphs and not src_doc.tables:
- messagebox.showwarning("提示", f"跳过空文档: {filename}")
- continue
-
- # 添加文件名标题(首文件不加分页符)
- if i > 0:
- merged_doc.add_page_break()
-
- # 插入带格式的文件名段落
- para = merged_doc.add_paragraph(filename)
- para.style.font.bold = True
- para.style.font.size = Pt(16)
-
- # 创建新分节并设置方向
- new_section = merged_doc.add_section()
- if src_doc.sections[0].orientation != initial_orientation:
- new_section.orientation = src_doc.sections[0].orientation
- new_section.page_width = src_doc.sections[0].page_width
- new_section.page_height = src_doc.sections[0].page_height
-
- # 将文件名段落移动到新分节
- merged_doc.element.body[-2].addprevious(para._p)
-
- # 深度复制段落和表格到新分节
- for element in src_doc.element.body:
- if element.tag.endswith('sectPr'):
- continue
- new_element = copy.deepcopy(element)
- new_section._sectPr.addprevious(new_element)
-
- # 释放内存
- src_doc.save(filename)
- del src_doc
-
- # 更新进度条(通过after调度到主线程)
- progress = (i + 1) / total_files * 100
- create_gui.root.after(0, create_gui.progress_bar.config, {'value': progress})
-
- # 保存最终文档
- output_filename = 'merged.docx'
- merged_doc.save(output_filename)
- messagebox.showinfo("完成", f"文档合并完成,结果保存为{output_filename}")
- create_gui.progress_bar.config(value=0) # 重置进度条
- create_gui.merge_button.config(state=tk.NORMAL) # 恢复按钮状态
- def select_folder():
- global selected_folder
- folder_path = filedialog.askdirectory()
- if folder_path:
- selected_folder = folder_path
- create_gui.merge_button.config(state=tk.NORMAL) # 启用合并按钮
- messagebox.showinfo("提示", "文件夹选择成功,请点击开始合并")
- def start_merge():
- # 禁用按钮防止重复点击
- create_gui.merge_button.config(state=tk.DISABLED)
- # 启动合并线程
- threading.Thread(target=merge_docx_files).start()
- def create_gui():
- create_gui.root = tk.Tk() # 保存root引用
- create_gui.root.title("Word文档合并工具")
- create_gui.root.geometry("400x280") # 调整窗口高度
-
- label = tk.Label(create_gui.root, text="Word文档合并工具", font=("Arial", 16))
- label.pack(pady=10)
-
- select_btn = tk.Button(create_gui.root, text="选择文件夹", command=select_folder, width=20, height=2)
- select_btn.pack(pady=5)
-
- # 新增合并按钮(初始禁用)
- create_gui.merge_button = tk.Button(
- create_gui.root,
- text="开始合并",
- command=start_merge,
- width=20,
- height=2,
- state=tk.DISABLED
- )
- create_gui.merge_button.pack(pady=5)
-
- # 新增进度条
- create_gui.progress_bar = ttk.Progressbar(
- create_gui.root,
- orient='horizontal',
- length=300,
- mode='determinate'
- )
- create_gui.progress_bar.pack(pady=15)
-
- footer = tk.Label(create_gui.root, text="@ Word文档合并工具 v1.1", font=("Arial", 10), fg="gray")
- footer.pack(side=tk.BOTTOM, pady=10)
-
- create_gui.root.mainloop()
- if __name__ == "__main__":
- create_gui()
复制代码
最终发布为exe可执行文件,下载地址:
|
|