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理論與實踐》課程目錄

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章