欢迎去往我的github

python generated .Doc File

笔记软件在2023/3/28 18:33:29推送该笔记

使用python实现Doc文档的生成

from docx import Document
from docx.shared import Cm,Pt
from docx.document import Document as Doc
from docx.oxml.ns import qn
#构建doc对象
document = Document()

#操作文档标题
document.add_heading('这是python写的!',0)

#操作段落文本
p = document.add_paragraph('我喜欢python,因为python可以做许多事情...')
#段落添加内容
run = p.add_run('大家也可以来学习!')
#对run内容加粗
run.bold = True
#设置run字体
run.font.size = Pt(18)
font = run.font
font.name = 'Calibri'
font.size = Pt(50)
#标题级别设置
document.add_heading('我是一级标题',level=1)
document.styles['Normal'].font.name = u'宋体' 
document.styles['Normal']._element.rPr.rFonts.set(qn('w:eastAsia'), u'宋体')


# 添加有序列表
document.add_paragraph(
    '我是有序列表1', style='List Number'
)
document.add_paragraph(
    '我是有序列表1', style='List Number'
)
#操作图片(图片所在路径)
# document.add_picture('刘亦菲.png', width=Cm(5.2))

# 添加无序列表
document.add_paragraph(
    '我是无序列表1', style='List Bullet'
)
document.add_paragraph(
    '我是无序列表2', style='List Bullet'
)

# 设置表格内容
records = (
    ('孙悟空', '男', '1111-1-1'),
    ('白骨精', '女', '2222-2-2')
)
# 添加表格,rows设置行 cols设置列
table = document.add_table(rows=1, cols=3)
hdr_cells = table.rows[0].cells
#设置列名
hdr_cells[0].text = '姓名'
hdr_cells[1].text = '性别'
hdr_cells[2].text = '出生日期'
# 操作写入行
for name, sex, birthday in records:
    row_cells = table.add_row().cells
    row_cells[0].text = name
    row_cells[1].text = sex
    row_cells[2].text = birthday

#保存doc文档
document.save('demo.docx')


posted @   月夜魂归  阅读(28)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· 写一个简单的SQL生成工具
· AI 智能体引爆开源社区「GitHub 热点速览」
· C#/.NET/.NET Core技术前沿周刊 | 第 29 期(2025年3.1-3.9)
欢迎这位客官来到《python generated .Doc File - 月夜魂归 - 博客园》
点击右上角即可分享
微信分享提示