python办公代码_[Python] 自动化办公 docx操作Word基础代码
轉載請注明:陳熹 chenx6542@foxmail.com (簡書號:半為花間酒)
若公眾號內轉載請聯系公眾號:早起Python
文中的截圖均為原創,轉載請注明來源
安裝
docx 是一個非標準庫,需要在命令行中安裝
命令行:
Windows:徽標鍵 + R —— 輸入cmd + 回車
pip install python-docx
Mac:打開終端/Terminal輸入
pip3 install python-docx
一定要注意,安裝的時候是 python-docx ,而實際調用時均為 docx
前置知識
Word中一般可以結構化成三個部分:
文檔 Document
段落 Paragraph
文字塊 Run
也就是 Document - Paragraph - Run 三級結構,這是最普遍的情況
其中文字塊 Run 最難理解,并不能完成按照圖中所示,兩個符號之間的短句是文字塊。通常情況下可以這么理解,但假如這個短句子中有多種不同的 樣式,則會被劃分成多個文字塊,以圖中的第一個黃圈為例,如果給這個短句添加一些細節:
此時就有4個文字塊
有時候一個Word文檔中是存在表格的,這時就會新的文檔結構產生
這時的結構非常類似Excel,可以看成Document - Table - Row/Column - Cell 四級結構
讀取Word
1. 打開Word
from docx import Document
path = ...
wordfile = Document(path)
2. 獲取段落
一個word文件由一個或者多個paragraph段落組成
paragraphs = wordfile.paragraphs
print(paragraphs)
3. 獲取段落文本內容
用 .text 獲取文本
for paragraph in wordfile.paragraphs:
print(paragraph.text)
4. 獲取文字塊文本內容
一個paragraph段落由一個或者多個run文字塊組成
for paragraph in wordfile.paragraphs:
for run in paragraph.runs:
print(run.text)
5. 遍歷表格
上面的操作完成的經典三級結構的遍歷,遍歷表格非常類似
# 按行遍歷
for table in wordfile.tables:
for row in table.rows:
for cell in row.cells:
print(cell.text)
# 按列遍歷
for table in wordfile.tables:
for column in table.columns:
for cell in column.cells:
print(cell.text)
寫入Word
1. 創建Word
只要不指定路徑,就默認為創建新Word文件
from docx import Document
wordfile = Document()
2. 保存文件
對文檔的修改和創建都切記保存
wordfile.save(...)
... 放需要保存的路徑
3. 添加標題
wordfile.add_heading(…, level=…)
4. 添加段落
wordfile.add_paragraph(...)
wordfile = Document()
wordfile.add_heading('一級標題', level=1)
wordfile.add_paragraph('新的段落')
5. 添加文字塊
wordfile.add_run(...)
6. 添加分頁
wordfile.add_page_break(...)
7. 添加圖片
wordfile.add_picture(..., width=…, height=…)
設置樣式
1. 文字字體設置
2. 文字其他樣式設置
from docx import Document
from docx.shared import RGBColor, Pt
wordfile = Document(file)
for paragraph in wordfile.paragraphs:
for run in paragraph.runs:
run.font.bold = True # 加粗
run.font.italic = True # 斜體
run.font.underline = True # 下劃線
run.font.strike = True # 刪除線
run.font.shadow = True # 陰影
run.font.size = Pt(20) # 字號
run.font.color.rgb = RGBColor(255, 0, 0) # 字體顏色
3. 段落樣式設置
默認對齊方式是左對齊
總結
以上是生活随笔為你收集整理的python办公代码_[Python] 自动化办公 docx操作Word基础代码的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 斐波那契数列python递归 0、1、1
- 下一篇: xpath contains_Pytho