python使用docx模塊讀寫docx文件的方法與docx模塊常用方法詳解
一,docx模塊
Python可以利用python-docx模塊處理word文檔,處理方式是面向?qū)ο蟮?。也就是說python-docx模塊會把word文檔,文檔中的段落、文本、字體等都看做對象,對對象進(jìn)行處理就是對word文檔的內(nèi)容處理。
二,相關(guān)概念
如果需要讀取word文檔中的文字(一般來說,程序也只需要認(rèn)識word文檔中的文字信息),需要先了解python-docx模塊的幾個概念。
1,Document對象,表示一個word文檔。
2,Paragraph對象,表示word文檔中的一個段落
3,Paragraph對象的text屬性,表示段落中的文本內(nèi)容。
三,模塊的安裝和導(dǎo)入
需要注意,python-docx模塊安裝需要在cmd命令行中輸入pip install python-docx,如下圖表示安裝成功(最后那句英文Successfully installed,成功地安裝完成)
注意在導(dǎo)入模塊時,用的是import docx。
from docx import Document from docx.enum.text import WD_ALIGN_PARAGRAPH #設(shè)置對象居中、對齊等。 from docx.enum.text import WD_TAB_ALIGNMENT,WD_TAB_LEADER #設(shè)置制表符等 from docx.shared import Inches #設(shè)置圖像大小 from docx.shared import Pt #設(shè)置像素、縮進(jìn)等 from docx.shared import RGBColor #設(shè)置字體顏色 from docx.shared import Length #設(shè)置寬度
四,讀取word文本
#-*- conding:utf-8 -*-
import docx
file=docx.Document(r"F:\python從入門到放棄\7\2\wenjian.docx")
print('段落:'+str(len(file.paragraphs)))
#
# for para in file.paragraphs:
# print(para.text)
for i in range(len(file.paragraphs)):
print("第"+str(i)+"段的內(nèi)容是:"+file.paragraphs[i].text)
五,寫word文本
#-*- conding:utf-8 -*-
import sys
from docx import Document
from docx.shared import Inches
def main():
# reload(sys)
# sys.setdefaultencoding('utf-8')
# 創(chuàng)建文檔對象
document = Document()
# 設(shè)置文檔標(biāo)題,中文要用unicode字符串
document.add_heading(u'我的一個新文檔',0)
# 往文檔中添加段落
p = document.add_paragraph('This is a paragraph having some ')
p.add_run('bold ').bold = True
p.add_run('and some ')
p.add_run('italic.').italic = True
# 添加一級標(biāo)題
document.add_heading(u'一級標(biāo)題, level = 1',level = 1)
document.add_paragraph('Intense quote',style = 'IntenseQuote')
# 添加無序列表
document.add_paragraph('first item in unordered list',style = 'ListBullet')
# 添加有序列表
document.add_paragraph('first item in ordered list',style = 'ListNumber')
document.add_paragraph('second item in ordered list',style = 'ListNumber')
document.add_paragraph('third item in ordered list',style = 'ListNumber')
# 添加圖片,并指定寬度
document.add_picture('cat.png',width = Inches(2.25))
# 添加表格: 1行3列
table = document.add_table(rows = 1,cols = 3)
# 獲取第一行的單元格列表對象
hdr_cells = table.rows[0].cells
# 為每一個單元格賦值
# 注:值都要為字符串類型
hdr_cells[0].text = 'Name'
hdr_cells[1].text = 'Age'
hdr_cells[2].text = 'Tel'
# 為表格添加一行
new_cells = table.add_row().cells
new_cells[0].text = 'Tom'
new_cells[1].text = '19'
new_cells[2].text = '12345678'
# 添加分頁符
document.add_page_break()
# 往新的一頁中添加段落
p = document.add_paragraph('This is a paragraph in new page.')
# 保存文檔
document.save('demo1.doc')
if __name__ == '__main__':
main()
六,讀取表格
#-*- conding:utf-8 -*-
import docx
doc = docx.Document('wenjian.docx')
for table in doc.tables: # 遍歷所有表格
print('----table------')
for row in table.rows: # 遍歷表格的所有行
# row_str = '\t'.join([cell.text for cell in row.cells]) # 一行數(shù)據(jù)
# print row_str
for cell in row.cells:
print(cell.text, '\t',)
print() #換行
七,添加段落
document=docx.Document() # 創(chuàng)建一個空白文檔
document.styles['Normal'].font.name = '宋體' # 設(shè)置西文字體
document.styles['Normal']._element.rPr.rFonts.set(qn('w:eastAsia'), '宋體') # 設(shè)置中文字體
p = document.add_paragraph() # 添加一個段落
p.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.JUSTIFY # 設(shè)置對齊方式
p.paragraph_format.line_spacing_rule = WD_LINE_SPACING.ONE_POINT_FIVE # 設(shè)置行間距
p.paragraph_format.space_after = Pt(0) # 設(shè)置段后間距
run = p.add_run('content') # 延長段落
run.font.color.rgb = RGBColor(255, 0, 0) # 設(shè)置字體顏色
run.font.size = Pt(22) # 設(shè)置字號
run.font.bold = True # 設(shè)置下劃線
八,docx模塊其它常用方法
字號與磅值的關(guān)系
| 字號 | 磅值 |
|---|---|
| 八號 | 5 |
| 七號 | 5.5 |
| 小六 | 6.5 |
| 六號 | 7.5 |
| 小五 | 9 |
| 五號 | 10.5 |
| 小四 | 12 |
| 四號 | 14 |
| 小三 | 15 |
| 三號 | 16 |
| 小二 | 18 |
| 二號 | 22 |
| 小一 | 24 |
| 一號 | 26 |
| 小初 | 36 |
| 初號 | 42 |
新增頁眉
section=document.sections[0] header=section.header bt1=header.paragraphs[0] bt1.text='此處是頁眉1'
新增頭信息
t1=document.add_paragraph('此處Tetle信息','Title')
新增段落 及 向前插入段落
p1=document.add_paragraph('新增段落P1')
pin1=p1.insert_paragraph_before('在p1前插入段落pin1')
段落里設(shè)置參數(shù)樣式 或 指定.style來設(shè)置參數(shù)
p2=document.add_paragraph('新增段落p2并設(shè)置style類型',style='ListBullet')
p3=document.add_paragraph('新增段落p3并指定style類型')
p3.style='ListBullet'
添加標(biāo)題 可設(shè)置標(biāo)題級別1-9
h1=document.add_heading('此處默認(rèn)標(biāo)題1')
h2=document.add_heading('此處添加標(biāo)題2',level=2)
h3=document.add_heading('此處添加標(biāo)題3',level=3)
設(shè)置字體
通過.add_run來設(shè)置字體: 加粗、斜體、大小、顏色、下劃線
paragraph=document.add_paragraph()
r1=paragraph.add_run('通過.bold=True來設(shè)置粗體')
r1.bold=True
r1.style='Emphasis'
r2=paragraph.add_run('也可以')
r3=paragraph.add_run('\n通過.italic=True來設(shè)置斜體,\n通過.font.size來設(shè)置字體大小,\n通過.font.color.rgb=RGBColor來設(shè)置字體顏色')
r3.italic=True
r3.font.size=Pt(20)
r3.font.color.rgb=RGBColor(200,77,150)
| 方法 | 作用 |
|---|---|
| all_caps | 全部大寫字母 |
| bold | 加粗 |
| color | 字體顏色 |
| complex_script | 是否為“復(fù)雜代碼” |
| cs_bold | “復(fù)雜代碼”加粗 |
| cs_italic | “復(fù)雜代碼”斜體 |
| double_strike | 雙刪除線 |
| emboss | 文本以凸出頁面的方式出現(xiàn) |
| hidden | 隱藏 |
| imprint | 印記 |
| italic | 斜體 |
| name | 字體 |
| no_proof | 不驗證語法錯誤 |
| outline | 顯示字符的輪廓 |
| shadow | 陰影 |
| small_caps | 小型大寫字母 |
| snap_to_grid | 定義文檔網(wǎng)格時對齊網(wǎng)絡(luò) |
| strike | 刪除線 |
| subscript | 下標(biāo) |
| superscript | 上標(biāo) |
| underline | 下劃線 |
設(shè)置居中、左右對齊、縮進(jìn)、制表符
p4=document.add_paragraph('準(zhǔn)備開始設(shè)置居中、左右對齊、縮進(jìn)等')
p4.paragraph_format.alignment=WD_ALIGN_PARAGRAPH.CENTER
| 方法 | 作用 |
|---|---|
| LEFT | 左對齊 |
| CENTER | 文字居中 |
| RIGHT | 右對齊 |
| JUSTIFY | 本兩端對齊 |
設(shè)置縮進(jìn)
默認(rèn)Inches(0.5)等于四個空格
p5=document.add_paragraph('content')
p5.paragraph_format.left_indent=Inches(0.5)
設(shè)置首行縮進(jìn)
p5.paragraph_format.first_line_indent=Inches(0.5)
設(shè)置段落間距 分為段落前 和 段落后
p5.paragraph_format.space_before=Pt(30) p5.paragraph_format.space_after=Pt(12)
設(shè)置段落行距當(dāng)行距為最小值和固定值時,設(shè)置值單位是磅,用Pt;當(dāng)行間距為多倍行距時,設(shè)置值為數(shù)值。
p5.paragraph_format.line_spacing=Pt(30)
| 方法 | 作用 |
|---|---|
| SINGLE | 單倍行距(默認(rèn)) |
| ONE_POINT_FIVE | 1.5倍行距 |
| DOUBLE | 2倍行距 |
| AT_LEAST | 最小值 |
| EXACTLY | 固定值 |
| MULTIPLE | 多倍行距 |
paragraph.line_spacing_rule = WD_LINE_SPACING.EXACTLY #固定值 paragraph_format.line_spacing = Pt(18) # 固定值18磅 paragraph.line_spacing_rule = WD_LINE_SPACING.MULTIPLE #多倍行距 paragraph_format.line_spacing = 1.75
分頁屬性
p5.paragraph_format.keep_with_next = True
| 方法 | 作用 | 說明 |
|---|---|---|
| widow_control | 孤行控制 | 防止在頁面頂端單獨打印段落末行或在頁面底端單獨打印段落首行 |
| keep_with_next | 與下段同頁 | 防止在選中段落與后面一段間插入分頁符 |
| page_break_before | 段前分頁 | 在選中段落前插入分頁符 |
| keep_together | 段中不分頁 | 防止在段落中出現(xiàn)分頁符 |
添加分頁符
document.add_page_break()
p5=document.add_paragraph('.add_page_break()硬分頁,即使文本未滿')
添加表格、設(shè)置表格樣式
table=document.add_table(rows=2,cols=2) table.style='LightShading-Accent1'
選擇表格內(nèi)單元格、單元格賦值添加和改變內(nèi)容
cell=table.cell(0,1) cell.text='通過cell.text()來添加內(nèi)容'
選擇表格的行,通過索引,然后索引單元格
row=table.rows[1] row.cells[0].text='通過.add_table(,)來添加表格' row.cells[1].text='通過for row in table.rows內(nèi)嵌套 for cell in row.cells來循環(huán)輸出表格內(nèi)容'
for循環(huán)逐行輸出表格內(nèi)容
for row in table.rows: for cell in row.cells: print(cell.text)
len表格內(nèi)行列數(shù)
row_count=len(table.rows) col_count=len(table.columns) print(row_count,col_count,'現(xiàn)表格行列數(shù)') row=table.add_row() #逐步添加行 print(len(table.rows),len(table.columns),'添加后表格行列數(shù)')
添加另一個表格 及 指定表格樣式
table1=document.add_table(1,3) table1.style='LightShading-Accent2' #設(shè)置表格樣式
填充 標(biāo)題行
heading_cells=table1.rows[0].cells #獲取 行列標(biāo) heading_cells[0].text='Qtx' #為行列表內(nèi)的cell單元格 賦值 heading_cells[1].text='Sku' heading_cells[2].text='Des'
表格數(shù)據(jù)
items=( (7,'1024','plush kitens'), (3,'2042','furbees'), (1,'1288','french poodle collars,deluxe') )
為每個項目添加數(shù)據(jù)行
for item in items: cells=table1.add_row().cells cells[0].text=str(item[0]) cells[1].text=str(item[1]) cells[2].text=str(item[2])
添加圖片
document.add_picture('002592.png',width=Inches(2))
調(diào)整圖片大小,如下:
document.add_picture('demo.png', width=Inches(1.0), height=Inches(1.0))
若同時定義寬度和高度,則圖片會被拉伸或壓縮到指定大小;若僅定義寬度或高度,則圖會自適應(yīng)調(diào)整大小。
保存文檔
document.save('test.docx')
更多關(guān)于python使用docx模塊讀寫docx文件的方法與docx模塊常用方法請查看下面的相關(guān)鏈接
相關(guān)文章
Python實現(xiàn)掃描局域網(wǎng)活動ip(掃描在線電腦)
這篇文章主要介紹了Python實現(xiàn)掃描局域網(wǎng)活動ip(掃描在線電腦),本文直接給出實現(xiàn)代碼,需要的朋友可以參考下2015-04-04
python畫圖時設(shè)置分辨率和畫布大小的實現(xiàn)(plt.figure())
這篇文章主要介紹了python畫圖時設(shè)置分辨率和畫布大小的實現(xiàn)(plt.figure()),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-01-01
如何利用python實現(xiàn)圖片轉(zhuǎn)化字符畫
這篇文章主要介紹了如何利用python實現(xiàn)圖片轉(zhuǎn)化字符畫,文章圍繞主題展開詳細(xì)的內(nèi)容介紹,具有一定的參考價值,需要的小伙伴可以參考一下2022-06-06
python實現(xiàn)在列表中查找某個元素的下標(biāo)示例
這篇文章主要介紹了python實現(xiàn)在列表中查找某個元素的下標(biāo)示例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-11-11
Pandas數(shù)據(jù)類型自行變換及數(shù)據(jù)類型轉(zhuǎn)換失敗問題分析與解決
這篇文章主要介紹了Pandas數(shù)據(jù)類型自行變換及數(shù)據(jù)類型轉(zhuǎn)換失敗問題分析與解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-06-06
Python實現(xiàn)操作Redis所有類型的方法詳解
Redis作為一款高性能的NoSQL數(shù)據(jù)庫,越來越受到了廣大開發(fā)者的喜愛。本篇博客將介紹如何使用Python操作Redis的所有類型,以及一些高級用法,感興趣的可以了解一下2023-04-04

