杂物箱 | python word文档处理
1.安装库python-docx
2.新建word对象
from docx import Document
# 创建文档
document = Document()
# 导入文档
document = Document(xxx.docx)
3.添加内容
# 添加标题
document.add_heading('标题1', 1)
# 添加段落
document.add_paragraph(str)
# 添加图片
document.add_picture('pic.jpg')
4.编辑内容
# 调用内容
for para in document:
para.text()调用文本
# 调用图片
for rel in document.part._rels:
for rel in dict_rel:
rel = dict_rel[rel]
if "image" in rel.target_ref:
if not os.path.exists(result_path):
os.makedirs(result_path)
img_name = re.findall("/(.*)", rel.target_ref)[0]
word_name = os.path.splitext(word_path)[0]
if os.sep in word_name:
new_name = word_name.split('\\')[-1]
else:
new_name = word_name.split('/')[-1]
img_name = f'{new_name}-'+'.'+f'{img_name}'
5.保存内容
document.save('xxx.docx')