Python3 integrates python-docx module

python-docx module installation

pip install python-docx

Python-docx operation document process summary

# 第一步:打开文档,创建文档对象
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 actual combat to create Word documents

from docx import Document


# 创建文档对象
document = Document()
# 文档对象添加标题
document.add_heading('Docx 创建简单文档', 0)
# 文档对象添加文本(段落对象)
document.add_paragraph(u'文档对象添加文本')
# 文档对象保存
document.save("D:\\demo.docx")


 

Python-docx actual combat to create a Word document and add pictures

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 actual combat to create structured Word documents

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 actual combat read 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 actual combat creation form

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')

Guess you like

Origin blog.csdn.net/zhouzhiwengang/article/details/112504949