from docx import Document
# 创建一个新文档
doc = Document()
# 添加段落
para = doc.add_paragraph('Hello World!')
from docx.enum.style import WD_STYLE_TYPE
from docx.enum.text import WD_ALIGN_PARAGRAPH
# 添加标题
title = doc.add_heading('Document Title', level=1)
# 设置标题样式
title.style = doc.styles['Title']
# 设置段落对齐方式
para.alignment = WD_ALIGN_PARAGRAPH.CENTER
# 设置段落字体
font = para.add_run().font
font.name = 'Calibri'
font.size = Pt(12)
font.bold = True
from docx.shared import Cm
# 添加表格
table = doc.add_table(rows=2, cols=2)
# 设置表格样式
table.style = doc.styles['Table Grid']
# 设置单元格宽度
table.columns[0].width = Cm(3)
# 设置表格内容
table.cell(0, 0).text = 'Name'
table.cell(0, 1).text = 'Age'
table.cell(1, 0).text = 'John'
table.cell(1, 1).text = '30'
from docx.shared import Inches
# 添加图片
doc.add_picture('image.jpg', width=Inches(1.25))
# 设置图片样式
pic = doc.paragraphs[-1].runs[-1]
pic.alignment = WD_ALIGN_PARAGRAPH.CENTER
doc.save('example.docx')
标签:docx,python,doc,常用,add,text,table,import From: https://www.cnblogs.com/full-stack-linux-new/p/17343030.html