Python利用docx模塊實(shí)現(xiàn)快速操作word文件
一、基礎(chǔ)內(nèi)容
安裝第三方庫(kù)的時(shí)候安裝:python-docx
from docx import Document
Pt - 像素、Cm - 厘米、Inches - 英寸
from docx.shared import Pt, Cm, Inches, RGBColor
1. 基本概念
1)Document對(duì)象(文檔對(duì)象) - 代表一個(gè)word文件
2)heading(標(biāo)題)
3)paragraph(段落) - 一段文字
4) run - 多個(gè)run可以拼成一個(gè)段落,不同的run可以單獨(dú)設(shè)置不同的樣式
5)table(表格) - 多行多列的表格
6)picture(圖片) - 文檔中插入的圖片
2. 操作word文檔
1)創(chuàng)建空的word文檔
doc = Document()
2) 添加標(biāo)題
Document對(duì)象.add_heading(標(biāo)題內(nèi)容,level=1)
level的取值范圍是:1 ~ 9,如果是0表示普通段落
h1 = doc.add_heading('數(shù)據(jù)分析報(bào)告', level=1) # 添加一個(gè)一級(jí)標(biāo)題
3)添加段落
Document對(duì)象.add_paragraph(段落內(nèi)容)
3.1 直接添加整個(gè)段落文字 ```python
p1 = doc.add_paragraph('此次調(diào)研數(shù)據(jù)主要通過(guò)問(wèn)卷發(fā)放的形式獲取,在紫金港全校范圍內(nèi)開(kāi)展。樣本數(shù)據(jù)通過(guò)簡(jiǎn)單隨機(jī)抽樣和分層抽樣相結(jié)合的方法,進(jìn)行相對(duì)廣泛的數(shù)據(jù)采集與調(diào)研,選取的樣本量較大,獲得的數(shù)據(jù)客觀真實(shí)。以下為具體的數(shù)據(jù)分析結(jié)果:') h2 = doc.add_heading('一、總體情況', level=2)
3.2 分段添加段落問(wèn)題
段落對(duì)象.add_run(內(nèi)容)
p2 = doc.add_paragraph('共發(fā)放問(wèn)卷:') run = p2.add_run('320 份') run.font.color.rgb = RGBColor(255, 0, 0) p3 = doc.add_paragraph() run1 = p3.add_run('回收問(wèn)卷: ') run2 = p3.add_run('296 份') run3 = p3.add_run(',回收率') run4 = p3.add_run('92.5%')
添加分頁(yè)(換頁(yè))
doc.add_page_break() h3 = doc.add_heading('二、樣本代表性', level=2) h4 = doc.add_heading('(一)性別:分布', level=3)
4) 添加表格
Document對(duì)象.add_table(行數(shù), 列數(shù))
table = doc.add_table(3, 3, style="Light Grid") # 'Medium Grid' table.cell(0, 0).text = '性別' table.cell(0, 1).text = '人數(shù)' table.cell(1, 0).text = '男'
5)添加圖片
doc.add_paragraph()
如果添加圖片的時(shí)候沒(méi)有設(shè)置寬高,圖片按照原圖大小顯示
doc.add_picture('files/img1.png', width=Cm(13)) doc.add_picture('files/liubei.jpg', width=Cm(13))
保存word文檔
doc.save('files/demo1.docx')
二、單獨(dú)設(shè)置內(nèi)容樣式
from docx import Document from docx.shared import Pt, Cm, Inches, RGBColor from docx.enum.text import WD_PARAGRAPH_ALIGNMENT doc = Document()
1. 字體相關(guān)樣式
1.1 標(biāo)題相關(guān)樣式
h1 = doc.add_heading(level=1) run = h1.add_run('數(shù)據(jù)分析報(bào)告')
設(shè)置標(biāo)題的字體大小
h1.style.font.size = Pt(25)
設(shè)置文字顏色
h1.style.font.color.rgb = RGBColor(97, 197, 84)
文字居中(CENTER、LEFT、RIGHT)
h1.paragraph_format.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
設(shè)置字體名稱(chēng)(標(biāo)題的字體名稱(chēng)不能直接設(shè)置到標(biāo)題對(duì)象上的,需要設(shè)置到提供內(nèi)容的run對(duì)象上)
run.font.name = '楷體'
注意:英文字體對(duì)應(yīng)的字體名可以直接設(shè)置; 如果是中文字體名稱(chēng),必須加上下面這段代碼才會(huì)有效
注意:中文字體,必須先使用,再設(shè)置有效性
from docx.oxml.ns import qn r = run._element.rPr.rFonts r.set(qn('w:eastAsia'), '楷體') h1 = doc.add_heading(level=2) run = h1.add_run('hello world!') run.font.name = 'Arima Koshi'
1.2 段落相關(guān)樣式
p1 = doc.add_paragraph('此次調(diào)研數(shù)據(jù)主要通過(guò)問(wèn)卷發(fā)放的形式獲取,在紫金港全校范圍內(nèi)開(kāi)展。樣本數(shù)據(jù)通過(guò)簡(jiǎn)單隨機(jī)抽樣和分層抽樣相結(jié)合的方法,進(jìn)行相對(duì)廣泛的數(shù)據(jù)采集與調(diào)研,選取的樣本量較大,獲得的數(shù)據(jù)客觀真實(shí)。以下為具體的數(shù)據(jù)分析結(jié)果:')
注意:如果直接設(shè)置段落對(duì)象相關(guān)樣式,樣式會(huì)作用于整個(gè)文檔中所有的段落
p1.style.font.size = Pt(15) # 設(shè)置字體大小 p1.style.font.color.rgb = RGBColor(75, 0, 130) # 設(shè)置字體顏色 p1.style.font.bold = True # 是否加粗 p1.style.font.italic = True # 是否傾斜 p1.style.font.name = ‘宋體' # 設(shè)置字體名稱(chēng) r = p1.style._element.rPr.rFonts r.set(qn(‘w:eastAsia'), ‘宋體') p1.style.font.underline = True # 添加下劃線 p1.style.font.strike = True # 添加中劃線(刪除線) p1.style.font.shadow = True # 添加陰影效果
1.3 間距相關(guān)樣式
注意:間距相關(guān)樣式,只會(huì)作用于當(dāng)前段落對(duì)象
p1.paragraph_format.line_spacing = 1.5 # 設(shè)置行間距 p1.paragraph_format.space_before = Pt(120) # 段前間距 p1.paragraph_format.space_after = Pt(120) # 段后間距 p1.paragraph_format.first_line_indent = Pt(30) # 首行縮進(jìn) h2 = doc.add_heading('一、總體情況', level=2)
1.4 通過(guò)run添加樣式
p2 = doc.add_paragraph('共發(fā)放問(wèn)卷:') p2.style.font.bold = True run = p2.add_run('320 份') run.font.color.rgb = RGBColor(255, 0, 0) p3 = doc.add_paragraph() run1 = p3.add_run('回收問(wèn)卷: ') run1.font.bold = True run2 = p3.add_run('296 份') run2.font.size = Pt(18) run3 = p3.add_run(',回收率') run3.font.italic = True run4 = p3.add_run('92.5%') run4.font.color.rgb = RGBColor(0, 0, 200) print(p3.runs) h3 = doc.add_heading('二、樣本代表性', level=2)
段落對(duì)象.runs - 獲取構(gòu)建整個(gè)段落的所有的run對(duì)象, 返回列表
直接創(chuàng)建段落對(duì)象的時(shí)候,會(huì)自動(dòng)在段落中創(chuàng)建段落內(nèi)容對(duì)應(yīng)的run對(duì)象
p4 = doc.add_paragraph('通過(guò)最終問(wèn)卷統(tǒng)計(jì)情況來(lái)看,此次問(wèn)卷發(fā)放充分考慮到性別、專(zhuān)業(yè)大類(lèi)以及年級(jí)的分布情況,樣本分布合理,所選取的樣本具有相對(duì)的典型性與代表性,可以以此為樣本進(jìn)行總體的推斷統(tǒng)計(jì)以及之后的相關(guān)分析。樣本具體分布情況如下:') p4.runs[0].font.size = Pt(15) p4.runs[0].font.color.rgb = RGBColor(70, 130, 180) p4.runs[0].font.underline = True h4 = doc.add_heading('(一)性別:分布', level=3) table = doc.add_table(3, 3) table.cell(0, 0).text = '性別' table.cell(0, 1).text = '人數(shù)' table.cell(1, 0).text = '男' doc.add_paragraph() doc.add_picture('files/img1.png', width=Cm(13)) doc.add_picture('files/liubei.jpg', width=Cm(13)) doc.save('files/demo2.docx')
三、樣式演示
from docx import Document from docx.enum.style import WD_STYLE_TYPE doc = Document() # 1.獲取所有已經(jīng)寫(xiě)好的主題樣式 styles = doc.styles for s in styles: print(s) print('------------------------------------------華麗的分割線------------------------------------------------') # 2. 字符樣式 - 設(shè)置在run對(duì)象上的樣式 doc.add_heading('===========1.所有的字符樣式名和對(duì)應(yīng)的效果============') # 獲取所有字符相關(guān)的樣式的名稱(chēng)和顯示效果 p1 = doc.add_paragraph() for s in styles: # Character if s.type == WD_STYLE_TYPE.CHARACTER: run = p1.add_run(f'字符樣式名稱(chēng): {s.name}\n', style=s) # 使用方法: p2 = doc.add_paragraph() p2.add_run('Hello World!', style='Intense Reference') print('------------------------------------------華麗的分割線------------------------------------------------') # 3. 段落樣式 - 設(shè)置在段落對(duì)象上的樣式 doc.add_heading('===========2.所有段落樣式名和對(duì)應(yīng)的效果============') for s in styles: if s.type == WD_STYLE_TYPE.PARAGRAPH: doc.add_paragraph(f'段落樣式名稱(chēng):{s.name}', style=s) doc.add_paragraph('hello world!', 'Title') print('------------------------------------------華麗的分割線------------------------------------------------') # 4. 表格樣式 - 設(shè)置在表格對(duì)象上的樣式 for s in styles: if s.type == WD_STYLE_TYPE.TABLE: doc.add_paragraph(f'表格樣式名稱(chēng):{s.name}') doc.add_table(3, 3, style=s) doc.add_paragraph('\n') doc.add_table(5, 4, style='Medium Grid 1 Accent 4') doc.save('files/demo3.docx')
四、制作表格
from docx import Document
from docx.shared import Pt, Cm, RGBColor
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
from docx.enum.table import WD_CELL_VERTICAL_ALIGNMENT
表格基本概念:table(表格)、row(行)
doc = Document()
1. 表格
1.1創(chuàng)建一個(gè)表格
table = doc.add_table(3, 3, style="Light Shading Accent 4") table.cell(2, 0).text = 'abc' table.cell(0, 0).text = '姓名' table.cell(0, 1).text = '年齡' table.cell(0, 2).text = '分?jǐn)?shù)' table.cell(1, 1).text = '19' table.cell(1, 3).text = '你好'
1.2添加行列
table.add_row() # 在最下面添加一行 table.add_column(Pt(100)) # 在最右邊添加一列
1.3 設(shè)置表格樣式
設(shè)置表格樣式,會(huì)作用于整個(gè)表格中所有的單元格
table.style.font.size = Pt(15) table.style.font.color.rgb = RGBColor(223, 178, 56) table.style.paragraph_format.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
2.行列對(duì)象
print(table.rows) # 獲取所有的行(返回一個(gè)容器,容器中的元素是所有的行對(duì)象) print(table.columns) # 獲取所有的列
遍歷獲取所有的行
for row in table.rows: # 獲取指定行所有的單元格 print(row.cells) # 獲取指定行的高度 print(row.height) # 獲取指定行的下標(biāo)(下標(biāo)值從0開(kāi)始) print(row._index) # 修改每一行的高度 # row.height = Pt(50) # 單獨(dú)設(shè)置指定行的高度 if row._index == 0: row.height = Pt(50) print('------------------------------------------華麗的分割線------------------------------------------------')
3. 單元格對(duì)象
3.1獲取單元格
cell1 = table.cell(0, 0) cell2 = table.cell(0, 1) cell3 = table.cell(1, 1) cell4 = table.cell(2, 2) cell5 = table.cell(1, 2)
3.2修改單元格內(nèi)容
cell1.text = 'Name' cell4.text = '98分' print(cell5.paragraphs) # [<docx.text.paragraph.Paragraph object at 0x7f81e012a490>] p = cell5.paragraphs[0] r1 = p.add_run('100') r2 = p.add_run('分') r2.font.color.rgb = RGBColor(255, 0, 0)
3.3 合并單元格(只能列合并)
cell11 = table.cell(3, 1) cell22 = table.cell(3, 2) cell33 = table.cell(3, 3) cell11.merge(cell22) cell11.merge(cell33)
3.4 設(shè)置單元格樣式
設(shè)置垂直對(duì)齊方式(TOP、BOTTOM、CENTER)
cell1.vertical_alignment = WD_CELL_VERTICAL_ALIGNMENT.CENTER p1 = cell1.paragraphs[0] run1 = p1.runs[0]
設(shè)置字體
run1.font.color.rgb = RGBColor(200, 10, 10) run1.font.size = Pt(20)
設(shè)置水平對(duì)齊方式(LEFT\RIGHT\CENTER)
p1.paragraph_format.alignment = WD_PARAGRAPH_ALIGNMENT.LEFT ??????? doc.save('files/demo4.docx')
到此這篇關(guān)于Python利用docx模塊實(shí)現(xiàn)快速操作word文件的文章就介紹到這了,更多相關(guān)Python docx操作word內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python運(yùn)維之獲取系統(tǒng)CPU信息的實(shí)現(xiàn)方法
今天小編就為大家分享一篇Python運(yùn)維之獲取系統(tǒng)CPU信息的實(shí)現(xiàn)方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-06-06Python?類(lèi)方法和靜態(tài)方法之間的區(qū)別
這篇文章主要介紹了Python?類(lèi)方法和靜態(tài)方法之間的區(qū)別,靜態(tài)方法并不是真正意義上的類(lèi)方法,它只是一個(gè)被放到類(lèi)里的函數(shù)而已,更多內(nèi)容需要的朋友可以參考一下2022-07-07python:解析requests返回的response(json格式)說(shuō)明
這篇文章主要介紹了python:解析requests返回的response(json格式)說(shuō)明,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-04-04python3在同一行內(nèi)輸入n個(gè)數(shù)并用列表保存的例子
今天小編就為大家分享一篇python3在同一行內(nèi)輸入n個(gè)數(shù)并用列表保存的例子,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-07-07TensorFlow實(shí)現(xiàn)卷積神經(jīng)網(wǎng)絡(luò)
這篇文章主要為大家詳細(xì)介紹了TensorFlow實(shí)現(xiàn)卷積神經(jīng)網(wǎng)絡(luò),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-05-05