Python3 集成python-docx 模块解析
虾米哥
阅读:759
2021-03-31 12:52:12
评论:0
python-docx 模块安装
pip install python-docx
python-docx 操作文档流程总结
# 第一步:打开文档,创建文档对象
document = Document()
# 第二步:添加标题
document.add_heading('Docx 创建简单文档', 0)
# 第三步:添加段落(返回段落对象)
paragraph = document.add_paragraph(u'文档对象添加文本')
# 第四步:添加分页符
document.add_page_break()
# 第五步:添加表格(返回表格对象)
table = document.add_table(rows=1, cols=3)
python-docx实战之创建Word文档
from docx import Document
# 创建文档对象
document = Document()
# 文档对象添加标题
document.add_heading('Docx 创建简单文档', 0)
# 文档对象添加文本(段落对象)
document.add_paragraph(u'文档对象添加文本')
# 文档对象保存
document.save("D:\\demo.docx")
python-docx实战之创建Word文档并添加图片
from docx.shared import Inches
from docx import Document
# 创建文档对象
document = Document()
# 文档对象添加标题
document.add_heading('Docx 创建简单文档添加图片', 0)
# 添加一个段落
document.add_paragraph(u'文档对象添加图片')
# 添加一张图片
document.add_picture('D:\\demo.png', width=Inches(5.5))
# 文档对象保存
document.save("D:\\imgDemo.docx")
python-docx实战之创建结构型Word 文档
from docx import Document
# 新建文档对象
document = Document()
# 文档对象添加标题
document.add_paragraph(u'Docx 创建结构化文档', 'Title')
# 文档对象添加子标题
document.add_paragraph(u'作者', 'Subtitle')
# 文档对象添加摘要
document.add_paragraph(u'摘要:本文阐述Python 优势', 'Body Text 2')
# 文档对象添加标题一
document.add_paragraph(u'简单', 'Heading 1')
# 文档对象添加指定标题内容
document.add_paragraph(u'易学')
# 文档对象添加标题二
document.add_paragraph(u'易用', 'Heading 2')
# 文档对象添加指定标题内容
document.add_paragraph(u'功能强大')
# 指定段落样式
paragraph = document.add_paragraph(u'Python 学习之路')
paragraph.style = "Heading 2"
# 文档保存
document.save('D:\\demo1.docx')
python-docx实战之读取Word
from docx import Document
# 指定docx 文件路径
path = "D:\\demo1.docx"
# 实例化docx 对象
document = Document(path)
# 遍历输出docx 对象涉及段落
for p in document.paragraphs:
# 输出段落文本长度
print(len(p.text))
# 数据段落引用样式
print(p.style.name)
python-docx实战之创建表格
from docx import Document
# 新建文档
document = Document()
# 增加表格,这是表格头
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 = '职业'
# 这是表格数据
records = (
(1, '张三', '电工'),
(2, '张五', '老板'),
(3, '马六', 'IT')
)
# 遍历数据并展示
for id, name, work in records:
row_cells = table.add_row().cells
row_cells[0].text = str(id)
row_cells[1].text = name
row_cells[2].text = work
# 手动增加分页
document.add_page_break()
# 保存文件
document.save('D:\\demo2.docx')
声明
1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。