热搜词
发表于 前天 15:57 | 显示全部楼层 |阅读模式
实战案例:用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",代码如下:
  1. import os
  2. import copy
  3. from docx import Document
  4. from docx.enum.section import WD_ORIENT
  5. from docx.oxml.shared import qn
  6. from docx.shared import Pt
  7. from tqdm import tqdm

  8. def merge_docx_files():
  9.     # 文件扫描与筛选
  10.     all_files = [f for f in os.listdir('.') if f.endswith('.docx')]
  11.     source_files = [f for f in all_files if not f.lower().startswith('merged')]
  12.     source_files.sort()

  13.     if not source_files:
  14.         print("未找到可合并的Word文档")
  15.         return

  16.     # 初始化目标文档
  17.     # 获取首文件页面方向
  18.     first_doc = Document(source_files[0])
  19.     first_section = first_doc.sections[0]
  20.    
  21.     # 根据首文件初始化目标文档
  22.     merged_doc = Document()
  23.     initial_section = merged_doc.sections[0]
  24.     initial_section.orientation = first_section.orientation
  25.     initial_section.page_width = first_section.page_width
  26.     initial_section.page_height = first_section.page_height
  27.     initial_orientation = initial_section.orientation

  28.     # 创建进度条
  29.     progress = tqdm(source_files, desc="正在合并文档")

  30.     # 内容合并处理
  31.     for i, filename in enumerate(progress):
  32.         src_doc = Document(filename)
  33.         
  34.         # 跳过空文档
  35.         if not src_doc.paragraphs and not src_doc.tables:
  36.             progress.write(f"跳过空文档: {filename}")
  37.             continue
  38.         
  39.         # 添加文件名标题(首文件不加分页符)
  40.         if i > 0:
  41.             merged_doc.add_page_break()
  42.         
  43.         # 插入带格式的文件名段落
  44.         para = merged_doc.add_paragraph(filename)
  45.         para.style.font.bold = True
  46.         para.style.font.size = Pt(16)
  47.         
  48.         # 创建新分节并设置方向
  49.         new_section = merged_doc.add_section()
  50.         if src_doc.sections[0].orientation != initial_orientation:
  51.             new_section.orientation = src_doc.sections[0].orientation
  52.             new_section.page_width = src_doc.sections[0].page_width
  53.             new_section.page_height = src_doc.sections[0].page_height
  54.         
  55.         # 将文件名段落移动到新分节
  56.         merged_doc.element.body[-2].addprevious(para._p)
  57.         
  58.         # 深度复制段落和表格到新分节
  59.         for element in src_doc.element.body:
  60.             if element.tag.endswith('sectPr'):
  61.                 continue
  62.             new_element = copy.deepcopy(element)
  63.             new_section._sectPr.addprevious(new_element)
  64.         
  65.         # 释放内存
  66.         src_doc.save(filename)
  67.         del src_doc
  68.    
  69.     # 保存最终文档
  70.     merged_doc.save('merged.docx')
  71.    
  72. if __name__ == "__main__":
  73.     merge_docx_files()
  74.     print("文档合并完成,结果保存为merged.docx")
复制代码

又改成了图形界面,代码为:
  1. import os
  2. import copy
  3. from docx import Document
  4. from docx.enum.section import WD_ORIENT
  5. from docx.oxml.shared import qn
  6. from docx.shared import Pt
  7. import tkinter as tk
  8. from tkinter import ttk, filedialog, messagebox  # 新增ttk导入
  9. import threading

  10. selected_folder = None  # 全局变量保存选择的文件夹路径

  11. def merge_docx_files():
  12.     if not selected_folder:
  13.         return
  14.    
  15.     os.chdir(selected_folder)
  16.     # 文件扫描与筛选
  17.     all_files = [f for f in os.listdir('.') if f.endswith('.docx')]
  18.     source_files = [f for f in all_files if not f.lower().startswith('merged')]
  19.     source_files.sort()

  20.     if not source_files:
  21.         messagebox.showinfo("提示", "未找到可合并的Word文档")
  22.         create_gui.merge_button.config(state=tk.NORMAL)  # 恢复按钮状态
  23.         return

  24.     # 初始化目标文档
  25.     first_doc = Document(source_files[0])
  26.     first_section = first_doc.sections[0]
  27.    
  28.     merged_doc = Document()
  29.     initial_section = merged_doc.sections[0]
  30.     initial_section.orientation = first_section.orientation
  31.     initial_section.page_width = first_section.page_width
  32.     initial_section.page_height = first_section.page_height
  33.     initial_orientation = initial_section.orientation

  34.     total_files = len(source_files)
  35.     for i, filename in enumerate(source_files):
  36.         src_doc = Document(filename)
  37.         
  38.         # 跳过空文档
  39.         if not src_doc.paragraphs and not src_doc.tables:
  40.             messagebox.showwarning("提示", f"跳过空文档: {filename}")
  41.             continue
  42.         
  43.         # 添加文件名标题(首文件不加分页符)
  44.         if i > 0:
  45.             merged_doc.add_page_break()
  46.         
  47.         # 插入带格式的文件名段落
  48.         para = merged_doc.add_paragraph(filename)
  49.         para.style.font.bold = True
  50.         para.style.font.size = Pt(16)
  51.         
  52.         # 创建新分节并设置方向
  53.         new_section = merged_doc.add_section()
  54.         if src_doc.sections[0].orientation != initial_orientation:
  55.             new_section.orientation = src_doc.sections[0].orientation
  56.             new_section.page_width = src_doc.sections[0].page_width
  57.             new_section.page_height = src_doc.sections[0].page_height
  58.         
  59.         # 将文件名段落移动到新分节
  60.         merged_doc.element.body[-2].addprevious(para._p)
  61.         
  62.         # 深度复制段落和表格到新分节
  63.         for element in src_doc.element.body:
  64.             if element.tag.endswith('sectPr'):
  65.                 continue
  66.             new_element = copy.deepcopy(element)
  67.             new_section._sectPr.addprevious(new_element)
  68.         
  69.         # 释放内存
  70.         src_doc.save(filename)
  71.         del src_doc
  72.         
  73.         # 更新进度条(通过after调度到主线程)
  74.         progress = (i + 1) / total_files * 100
  75.         create_gui.root.after(0, create_gui.progress_bar.config, {'value': progress})
  76.    
  77.     # 保存最终文档
  78.     output_filename = 'merged.docx'
  79.     merged_doc.save(output_filename)
  80.     messagebox.showinfo("完成", f"文档合并完成,结果保存为{output_filename}")
  81.     create_gui.progress_bar.config(value=0)  # 重置进度条
  82.     create_gui.merge_button.config(state=tk.NORMAL)  # 恢复按钮状态


  83. def select_folder():
  84.     global selected_folder
  85.     folder_path = filedialog.askdirectory()
  86.     if folder_path:
  87.         selected_folder = folder_path
  88.         create_gui.merge_button.config(state=tk.NORMAL)  # 启用合并按钮
  89.         messagebox.showinfo("提示", "文件夹选择成功,请点击开始合并")


  90. def start_merge():
  91.     # 禁用按钮防止重复点击
  92.     create_gui.merge_button.config(state=tk.DISABLED)
  93.     # 启动合并线程
  94.     threading.Thread(target=merge_docx_files).start()


  95. def create_gui():
  96.     create_gui.root = tk.Tk()  # 保存root引用
  97.     create_gui.root.title("Word文档合并工具")
  98.     create_gui.root.geometry("400x280")  # 调整窗口高度
  99.    
  100.     label = tk.Label(create_gui.root, text="Word文档合并工具", font=("Arial", 16))
  101.     label.pack(pady=10)
  102.    
  103.     select_btn = tk.Button(create_gui.root, text="选择文件夹", command=select_folder, width=20, height=2)
  104.     select_btn.pack(pady=5)
  105.    
  106.     # 新增合并按钮(初始禁用)
  107.     create_gui.merge_button = tk.Button(
  108.         create_gui.root,
  109.         text="开始合并",
  110.         command=start_merge,
  111.         width=20,
  112.         height=2,
  113.         state=tk.DISABLED
  114.     )
  115.     create_gui.merge_button.pack(pady=5)
  116.    
  117.     # 新增进度条
  118.     create_gui.progress_bar = ttk.Progressbar(
  119.         create_gui.root,
  120.         orient='horizontal',
  121.         length=300,
  122.         mode='determinate'
  123.     )
  124.     create_gui.progress_bar.pack(pady=15)
  125.    
  126.     footer = tk.Label(create_gui.root, text="@ Word文档合并工具 v1.1", font=("Arial", 10), fg="gray")
  127.     footer.pack(side=tk.BOTTOM, pady=10)
  128.    
  129.     create_gui.root.mainloop()


  130. if __name__ == "__main__":
  131.     create_gui()
复制代码

最终发布为exe可执行文件,下载地址:

全部评论0
回复
您需要登录后才可以回帖 登录 | 注册

本版积分规则

QQ|Archiver|手机版|小黑屋|管理员之家 ( 苏ICP备2023053177号-2 )

GMT+8, 2025-6-6 09:31 , Processed in 0.169037 second(s), 23 queries .

Powered by Discuz! X3.5

Cpoyright © 2001-2025 Discuz! Team