Python自动化办公应用学习笔记49—Word文档自动化处理5
zhezhongyun 2025-09-01 19:11 26 浏览
七、高级功能
1.合并多个文档
from docxcompose.composer import Composer
def merge_documents(file_paths, output_path):
"""合并多个Word文档"""
master = Document(file_paths[0])
composer = Composer(master)
for path in file_paths[1:]:
doc = Document(path)
composer.append(doc)
composer.save(output_path)
2. 添加页码
from docx.oxml import OxmlElement
def add_page_number(footer):
run = footer.paragraphs[0].add_run()
fldChar = OxmlElement('w:fldChar')
fldChar.set('{http://schemas.openxmlformats.org/wordprocessingml/2006/main}fldCharType', 'begin')
run._r.append(fldChar)
run._r.append(OxmlElement('w:instrText').set('xml:space', 'preserve', ' PAGE'))
run._r.append(OxmlElement('w:fldChar').set('{http://schemas.openxmlformats.org/wordprocessingml/2006/main}fldCharType', 'end'))
动态页码
from docx.oxml import OxmlElement
def add_page_number(footer):
run = footer.paragraphs[0].add_run("第 ")
fldChar = OxmlElement('w:fldChar')
fldChar.set(qn('w:fldCharType'), 'begin')
run._r.append(fldChar)
instrText = OxmlElement('w:instrText')
instrText.set(qn('xml:space'), 'preserve')
instrText.text = "PAGE"
run._r.append(instrText)
fldChar = OxmlElement('w:fldChar')
fldChar.set(qn('w:fldCharType'), 'end')
run._r.append(fldChar)
run.add_run(" 页")
add_page_number(doc.sections[0].footer)
3.内容替换与标记
def replace_text(doc, old_text, new_text):
"""全局文本替换"""
for paragraph in doc.paragraphs:
if old_text in paragraph.text:
paragraph.text = paragraph.text.replace(old_text, new_text)
for table in doc.tables:
for row in table.rows:
for cell in row.cells:
if old_text in cell.text:
cell.text = cell.text.replace(old_text, new_text)
def highlight_keyword(doc, keyword):
"""高亮显示关键词"""
for paragraph in doc.paragraphs:
for run in paragraph.runs:
if keyword in run.text:
run.font.highlight_color = WD_COLOR_INDEX.YELLOW
run.font.bold = True
4.分页与分节控制
# 添加分页符
doc.add_page_break()
# 添加分节符(下一页)
doc.add_section()
# 添加分节符(连续)
from docx.enum.section import WD_SECTION
new_section = doc.add_section(WD_SECTION.CONTINUOUS)
5.文档差异比较
def compare_documents(doc1_path, doc2_path, output_html):
"""比较两个文档差异"""
from difflib import HtmlDiff
def get_paragraphs_text(doc_path):
doc = Document(doc_path)
return [p.text for p in doc.paragraphs]
doc1_text = get_paragraphs_text(doc1_path)
doc2_text = get_paragraphs_text(doc2_path)
html_diff = HtmlDiff().make_file(doc1_text, doc2_path)
with open(output_html, 'w', encoding='utf-8') as f:
f.write(html_diff)
6 提取图片
import re
from docx.parts.image import ImagePart
for rel in doc.part.rels.values():
if "image" in rel.target_ref:
image_part = rel.target_part
with open(f"image_{rel.rId}.png", "wb") as f:
f.write(image_part.blob)
八、性能优化
备份文档:操作前创建文档副本
错误处理:添加异常捕获机制
资源释放:及时关闭文档和Word进程
样式重用:使用预定义样式提高一致性
批量处理:使用循环处理多个文件
1.性能优化
# 批量处理优化示例
import os
def batch_process_folder(input_folder, output_folder, process_function):
"""批量处理文件夹中的文档"""
os.makedirs(output_folder, exist_ok=True)
for filename in os.listdir(input_folder):
if filename.endswith('.docx'):
input_path = os.path.join(input_folder, filename)
output_path = os.path.join(output_folder, filename)
try:
doc = Document(input_path)
process_function(doc) # 自定义处理函数
doc.save(output_path)
print(f"已处理: {filename}")
except Exception as e:
print(f"处理失败 {filename}: {str(e)}")
2.常见问题解决方案
问题 | 解决方案 |
中文字体不生效 | 同时设置font.name和w:eastAsia属性 |
表格格式混乱 | 使用预定义表格样式或明确设置列宽 |
页眉页脚不显示 | 检查分节链接状态和页面边距设置 |
大文档处理慢 | 分块处理,避免一次性加载整个文档 |
转换后的.doc内容丢失 | 使用pywin32保存为.docx格式再操作 |
图片插入后变形 | 计算并保持原始宽高比 |
相关推荐
- perl基础——循环控制_principle循环
-
在编程中,我们往往需要进行不同情况的判断,选择,重复操作。这些时候我们需要对简单语句来添加循环控制变量或者命令。if/unless我们需要在满足特定条件下再执行的语句,可以通过if/unle...
- CHAPTER 2 The Antechamber of M de Treville 第二章 特雷维尔先生的前厅
-
CHAPTER1TheThreePresentsofD'ArtagnantheElderCHAPTER2TheAntechamber...
- CHAPTER 5 The King'S Musketeers and the Cardinal'S Guards 第五章 国王的火枪手和红衣主教的卫士
-
CHAPTER3TheAudienceCHAPTER5TheKing'SMusketeersandtheCardinal'SGuard...
- CHAPTER 3 The Audience 第三章 接见
-
CHAPTER3TheAudienceCHAPTER3TheAudience第三章接见M.DeTrévillewasatt...
- 别搞印象流!数据说明谁才是外线防守第一人!
-
来源:Reddit译者:@assholeeric编辑:伯伦WhoarethebestperimeterdefendersintheNBA?Here'sagraphofStea...
- V-Day commemorations prove anti-China claims hollow
-
People'sLiberationArmyhonorguardstakepartinthemilitaryparademarkingthe80thanniversary...
- EasyPoi使用_easypoi api
-
EasyPoi的主要特点:1.设计精巧,使用简单2.接口丰富,扩展简单3.默认值多,writelessdomore4.springmvc支持,web导出可以简单明了使用1.easypoi...
- 关于Oracle数据库12c 新特性总结_oracle数据库12514
-
概述今天主要简单介绍一下Oracle12c的一些新特性,仅供参考。参考:http://docs.oracle.com/database/121/NEWFT/chapter12102.htm#NEWFT...
- 【开发者成长】JAVA 线上故障排查完整套路!
-
线上故障主要会包括CPU、磁盘、内存以及网络问题,而大多数故障可能会包含不止一个层面的问题,所以进行排查时候尽量四个方面依次排查一遍。同时例如jstack、jmap等工具也是不囿于一个方面的问题...
- 使用 Python 向多个地址发送电子邮件
-
在本文中,我们将演示如何使用Python编程语言向使用不同电子邮件地址的不同收件人发送电子邮件。具体来说,我们将向许多不同的人发送电子邮件。使用Python向多个地址发送电子邮件Python...
- 提高工作效率的--Linux常用命令,能够决解95%以上的问题
-
点击上方关注,第一时间接受干货转发,点赞,收藏,不如一次关注评论区第一条注意查看回复:Linux命令获取linux常用命令大全pdf+Linux命令行大全pdf为什么要学习Linux命令?1、因为Li...
- linux常用系统命令_linux操作系统常用命令
-
系统信息arch显示机器的处理器架构dmidecode-q显示硬件系统部件-(SMBIOS/DMI)hdparm-i/dev/hda罗列一个磁盘的架构特性hdparm-tT/dev/s...
- 小白入门必知必会-PostgreSQL-15.2源码编译安装
-
一PostgreSQL编译安装1.1下载源码包在PostgreSQL官方主页https://www.postgresql.org/ftp/source/下载区选择所需格式的源码包下载。cd/we...
- Linux操作系统之常用命令_linux系统常用命令详解
-
Linux操作系统一、常用命令1.系统(1)系统信息arch显示机器的处理器架构uname-m显示机器的处理器架构uname-r显示正在使用的内核版本dmidecode-q显示硬件系...
- linux网络命名空间简介_linux 网络相关命令
-
此篇会以例子的方式介绍下linux网络命名空间。此例中会创建两个networknamespace:nsa、nsb,一个网桥bridge0,nsa、nsb中添加网络设备veth,网络设备间...
- 一周热门
- 最近发表
-
- perl基础——循环控制_principle循环
- CHAPTER 2 The Antechamber of M de Treville 第二章 特雷维尔先生的前厅
- CHAPTER 5 The King'S Musketeers and the Cardinal'S Guards 第五章 国王的火枪手和红衣主教的卫士
- CHAPTER 3 The Audience 第三章 接见
- 别搞印象流!数据说明谁才是外线防守第一人!
- V-Day commemorations prove anti-China claims hollow
- EasyPoi使用_easypoi api
- 关于Oracle数据库12c 新特性总结_oracle数据库12514
- 【开发者成长】JAVA 线上故障排查完整套路!
- 使用 Python 向多个地址发送电子邮件
- 标签列表
-
- HTML 教程 (33)
- HTML 简介 (35)
- HTML 实例/测验 (32)
- HTML 测验 (32)
- JavaScript 和 HTML DOM 参考手册 (32)
- HTML 拓展阅读 (30)
- HTML文本框样式 (31)
- HTML滚动条样式 (34)
- HTML5 浏览器支持 (33)
- HTML5 新元素 (33)
- HTML5 WebSocket (30)
- HTML5 代码规范 (32)
- HTML5 标签 (717)
- HTML5 标签 (已废弃) (75)
- HTML5电子书 (32)
- HTML5开发工具 (34)
- HTML5小游戏源码 (34)
- HTML5模板下载 (30)
- HTTP 状态消息 (33)
- HTTP 方法:GET 对比 POST (33)
- 键盘快捷键 (35)
- 标签 (226)
- HTML button formtarget 属性 (30)
- opacity 属性 (32)
- transition 属性 (33)