python-docx
库能够处理文档中的段落、表格、图片等,但对于文本框,页眉和页脚中的Shapes对象,python-docx
就显得力不从心了。这些复杂的对象通常需要利用Word的COM接口才能进行高级操作。
因此,如果你需要执行复杂的Word文档操作,尤其是涉及到宏、文本框、图表等,pywin32
是目前最好的选择。需要注意的是,pywin32
只能在安装了Microsoft Office的Windows操作系统上运行
import win32com.client as win32
from win32com.client import constants
def set_shape_text(shapes, old_text, new_text):
"""
这个函数接受一个shapes集合和两个字符串old_text与new_text,
只将文本内容为old_text的shapes更新为new_text。
"""
for shape in shapes:
if shape.TextFrame.HasText:
current_text = shape.TextFrame.TextRange.Text.strip() # 获取当前文本并去除空白
print(current_text) # 打印当前文本
if current_text == old_text: # 判断文本是否为指定的内容
print(f"Changing '{current_text}' to '{new_text}'")
shape.TextFrame.TextRange.Text = new_text # 更新文本内容
# 打开Word应用程序,设置为不可见运行
doc_app = win32.gencache.EnsureDispatch('Word.Application')
doc_app.Visible = 0 # 如果想让Word界面显示,将0改为1
# 此处为硬编码路径,也可以通过os.getcwd()动态获取
document_path = r'E:\Desktop\模板测试\测试1.docx'
doc = doc_app.Documents.Open(document_path)
# 打印文档中Shapes的数量
print(doc.Shapes.Count)
# 获取文档的第一节
wd_section = doc.Sections(1)
# 更新文档中所有Shapes的文本(只有当文本为"12mv"时)
set_shape_text(doc.Shapes, "12mv", "新内容2")
# 打印并更新页脚中Shape的文本(只有当文本为"12mv"时)
footer_shapes = wd_section.Footers(constants.wdHeaderFooterPrimary).Shapes
set_shape_text(footer_shapes, "12mv", "新内容1")
# 关闭文档并保存更改
doc.Close(SaveChanges=True)
# 退出Word应用程序
doc_app.Quit()