一 前言
word的操作也是經常必備的技能之一,今天有空整理了一份給大家!!加油喲!!
知識追尋者(Inheriting the spirit of open source, Spreading technology knowledge;)
二 操作Word
安裝 python-docx
pip install python-docx
2.1 讀取word
word 中的存檔格式 爲 一個 Document 對象; 每個Document對象 包含許多 Paragraph
對象 和 table
對象;其中 Paragraph 對象 有許多行內元素 Run
對象; Run對象 又有 字體(font),數據(text),顏色(color),字號(size)等對象;table對象比較簡單,可以跟excel聯繫起來,就是由 行(row)列(column)組成;
讀取每段內容示例
from docx import Document
path = r'C:\mydata\generator\py\tt.docx'
# 獲取Document對象
doc = Document(path)
# 讀取每段
contents = [ paragraph.text for paragraph in doc.paragraphs]
# 讀取每行
for line in contents:
print(line)
Tip : 讀取時值讀取段落文本內容,其它內容不會被讀取進段落
讀取表格示例
from docx import Document
path = r'C:\mydata\generator\py\tt.docx'
# 獲取Document對象
doc = Document(path)
# 獲取所有表格
tables = [table for table in doc.tables]
for row in table.rows:
for cell in row.cells:
# 遍歷每個單元格內容
text = str(cell.text)
Tip: 讀取的是整個word的表格的單元格內容
2.2 寫入word
主要方法如下
- Document(); 新建空白文檔對象;
- add_heading(text, level=1) ; 寫入 標題 text 是內容,leve 是標題等級 0-9;
- add_paragraph(text, style);添加段落描述;text,是內容,styles設置風格
- add_paragraph(text, style).add_run( text, style);爲段落添加行,text,是內容,styles設置風格;
- add_picture(image_path_or_stream, width, height);分別是圖片地址,寬度,高度;
- add_page_break();插入分頁符
- add_table(rows, cols, style); 參數分別是 行數,列數,風格;
- add_table(rows, cols, style).rows() ;行數
- add_table(rows, cols, style).cols() ;列數
示例代碼
from docx import Document
from docx.shared import Pt
from docx.shared import Inches
from docx.oxml.ns import qn
from docx.shared import RGBColor
# 新建空白文檔
docx = Document()
# 創建標題
docx.add_heading('知識追尋者操作word',0)
# 創建一級標題
docx.add_heading('寫入段落示例',1)
# 添加段落描述
docx.add_paragraph('知識追尋者(Inheriting the spirit of open source, Spreading technology knowledge;)')
# 寫入一級標題
docx.add_heading('寫入行示例',1)
# 寫入行
run = docx.add_paragraph('公衆號:知識追尋者').add_run('快點關注吧')
# 設置字體大小
run.font.size = Pt(18)
# 設置字體
run.font.name='黑體'
# 設置字體顏色
run.font.color.rgb = RGBColor(0xFF, 0x00, 0x00)
# 設置粗體
run.bold = True
# 設置斜體
run.italic = True
docx.add_heading('寫入無序列表',2)
docx.add_paragraph(
'你是圓的啊!', style='List Bullet'
)
docx.add_heading('寫入有序列表',2)
docx.add_paragraph(
'你是方的啊!', style='List Number'
)
docx.add_heading('寫入表格',1)
# 新建1行3列的表
table = docx.add_table(rows=1, cols=3)
# 添加表頭
cells = table.rows[0].cells
cells[0].text = '編號'
cells[1].text = '姓名'
cells[2].text = '性別'
# 表格數據
records = ( (1, 'carry', 'girl'), (2, 'cherry', 'girl'), (3, 'bafei', 'boy'))
# 將表格數據加入表格
for id, name, gender in records:
row_cells = table.add_row().cells
row_cells[0].text = str(id)
row_cells[1].text = name
row_cells[2].text = gender
docx.add_heading('寫入圖片',1)
docx.add_picture('zszxz.jpg', width=Inches(1.0))
# 保存文件
docx.save('zszxz.docx')
結果
三 參考文檔
功能多內容參照官方文檔