from docx import Document
from docx.shared import Inches
from docx.shared import Pt
from docx.oxml.ns import qn
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
from docx.shared import Cm
from docx.shared import RGBColor
# 创建空文档
doc = Document()
# 添加标题,设置级别level,0为Title,1或省略为Heading 1,0<=level<=9
title=doc.add_heading('docx常用方法',0)
doc.add_heading('二级标题',1)
#设置文字位置(居中)
title.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
# 添加段落,参数为text=''和style=None
p = doc.add_paragraph('添加段落 ')
#段落文字居中设置
p.paragraph_format.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
# 添加空白段落
p = doc.add_paragraph()
#设置首行缩进0.74厘米,即2个字符
p.paragraph_format.first_line_indent = Cm(0.74)
# 添加run对象,参数为text=None和style=None,
# run对象有bold(加粗)和italic(斜体)这两个属性
p.add_run("测试1").bold = True
p.add_run("测试2").italic = True
#设置字号
p.add_run("测试3").font.size=Pt(24)
#设置字体颜色
p.add_run("测试4").font.color.rgb = RGBColor(255,0,0)
#设置中文字体
run=p.add_run("测试")
run.font.name='华文行楷'
run.element.rPr.rFonts.set(qn('w:eastAsia'), '华文行楷')
#设置英文字体
run=p.add_run("i-search")
run.font.name='Arial Black'
#插入图片
img_path=r"C:\Users\Administrator\Desktop\img_test.png"
doc.add_picture(img_path)
#添加表格(3行2列)
table = doc.add_table(rows=3, cols=2)
hdr_cells=table.rows[0].cells
hdr_cells[0].text="第一列"
hdr_cells[1].text="第二列"
hdr_cells = table.rows[1].cells
hdr_cells[0].text = '1'
hdr_cells[1].text = '2'
hdr_cells = table.rows[2].cells
hdr_cells[0].text = 'A'
hdr_cells[1].text = 'B'
#添加空白页
doc.add_page_break()
#文档储存
path=r"C:\Users\Administrator\Desktop\Test.docx"
#保存文档
doc.save(path)
这个必须点赞👍
啥套路 ❓
你这个套路有点深。。哈 😆
👍