Python办公自动化 4.2 Python操作word:python-docx 使用教程 操作word

课程大纲

第二章 Python10分钟入门
【2.1】:PyCharm社区版配置Anaconda开发环境
【2.2】:Python基础知识及正则表达式入门

第三章 Python操作Excel
【3.1】:xlrd 使用教程 读取 操作Excel
【3.2】:xlwt 使用教程 写入 操作Excel
【3.3】:xlutils 使用教程 修改 操作Excel
【3.4】:xlwings 使用教程 读取 写入 修改 操【作Excel
【3.5】:openpyxl 使用教程 读取 写入 修改 操作Excel
【3.6】:xlswriter 使用教程 读取 写入 修改 操作Excel
【3.7】:win32com 使用教程 读取 写入 修改 操作Excel
【3.8】:pandas 使用教程 读取 写入 修改 操作Excel

第四章 Python操作word
【4.1】:win32com 使用教程 操作word
【4.2】:python-docx 使用教程 操作word

第五章 Python操作ppt
【5.1】:win32com 使用教程 操作复制ppt PowerPoint
【5.2】:python-pptx 使用教程 操作ppt PowerPoint 添加文字 形状图表

至于 python-docx最好的老师应该是官方文档了,所有的操作上面都有说明。

文档地址:https://python-docx.readthedocs.io/en/latest/

4.2.1 pip安装python-docx

pip install python-docx

因为我之前已经安装过,所以提示已经安装:
image-20200616100608882

4.2.2 python-docx 操作word

官方例程:

from docx import Document
from docx.shared import Inches

document = Document()

document.add_heading('Document Title', 0)

p = document.add_paragraph('A plain paragraph having some ')
p.add_run('bold').bold = True
p.add_run(' and some ')
p.add_run('italic.').italic = True

document.add_heading('Heading, level 1', level=1)
document.add_paragraph('Intense quote', style='Intense Quote')

document.add_paragraph(
    'first item in unordered list', style='List Bullet'
)
document.add_paragraph(
    'first item in ordered list', style='List Number'
)

document.add_picture('monty-truth.png', width=Inches(1.25))

records = (
    (3, '101', 'Spam'),
    (7, '422', 'Eggs'),
    (4, '631', 'Spam, spam, eggs, and spam')
)

table = document.add_table(rows=1, cols=3)
hdr_cells = table.rows[0].cells
hdr_cells[0].text = 'Qty'
hdr_cells[1].text = 'Id'
hdr_cells[2].text = 'Desc'
for qty, id, desc in records:
    row_cells = table.add_row().cells
    row_cells[0].text = str(qty)
    row_cells[1].text = id
    row_cells[2].text = desc

document.add_page_break()

document.save('demo.docx')

执行效果:

image-20200616095659144


以上模块功能可能没列举全,大家有什么希望的操作可以直接留言,我收到留言后会增加相关操作示例(若有),并对文章进行更新,谢谢大家!

返回《Python办公自动化之Word、Excel、PPT理论与实践》课程目录

猜你喜欢

转载自blog.csdn.net/u014779536/article/details/106781364