读取文档模板
思路:先自己设置一个文档模板,定义好需要插入的位置,替换成特别的词语或语句。doc处理完一块替换,最后处理完保存为一个新的文件。
doc = Document(doc_model_path)
指定位置插入图片
插入这个图片的大小需要根据图片的比例调整,网上的一个大神写的
def add_pic_after(doc, par, photo_path,height,width):
for i, p in enumerate(doc.paragraphs): # 遍历所有的段落
if par in p.text:
p.runs[-1].add_break() # 添加一个折行
shape = p.runs[-1].add_picture(photo_path) # 在runs的最后一段文字后添加图片
shape.height = height
shape.width = width
os.remove(photo_path)
break
return doc
文字替换(正文)
def replace_text(doc, old_text, new_text):
# 遍历每个段落
for p in doc.paragraphs:
# 如果要搜索的内容在该段落
if old_text in p.text:
# 使用 runs 替换内容但不改变样式
for run in p.runs:
if old_text in run.text:
run.text = run.text.replace(old_text, new_text)
文字替换(表格)
def replace_table(table, old_text, new_text