本篇文章為大家展示了怎么在python中使用docx模塊讀寫docx文件,內(nèi)容簡(jiǎn)明扼要并且容易理解,絕對(duì)能使你眼前一亮,通過這篇文章的詳細(xì)介紹希望你能有所收獲。
為徐州等地區(qū)用戶提供了全套網(wǎng)頁(yè)設(shè)計(jì)制作服務(wù),及徐州網(wǎng)站建設(shè)行業(yè)解決方案。主營(yíng)業(yè)務(wù)為成都網(wǎng)站制作、網(wǎng)站建設(shè)、徐州網(wǎng)站設(shè)計(jì),以傳統(tǒng)方式定制建設(shè)網(wǎng)站,并提供域名空間備案等一條龍服務(wù),秉承以專業(yè)、用心的態(tài)度為用戶提供真誠(chéng)的服務(wù)。我們深信只要達(dá)到每一位用戶的要求,就會(huì)得到認(rèn)可,從而選擇與我們長(zhǎng)期合作。這樣,我們也可以走得更遠(yuǎn)!一,docx模塊
Python可以利用python-docx模塊處理word文檔,處理方式是面向?qū)ο蟮?。也就是說python-docx模塊會(huì)把word文檔,文檔中的段落、文本、字體等都看做對(duì)象,對(duì)對(duì)象進(jìn)行處理就是對(duì)word文檔的內(nèi)容處理。
二,相關(guān)概念
如果需要讀取word文檔中的文字(一般來說,程序也只需要認(rèn)識(shí)word文檔中的文字信息),需要先了解python-docx模塊的幾個(gè)概念。
1,Document對(duì)象,表示一個(gè)word文檔。
2,Paragraph對(duì)象,表示word文檔中的一個(gè)段落
3,Paragraph對(duì)象的text屬性,表示段落中的文本內(nèi)容。
三,模塊的安裝和導(dǎo)入
需要注意,python-docx模塊安裝需要在cmd命令行中輸入pip install python-docx,如下圖表示安裝成功(最后那句英文Successfully installed,成功地安裝完成)
注意在導(dǎo)入模塊時(shí),用的是import docx。
from docx import Document from docx.enum.text import WD_ALIGN_PARAGRAPH #設(shè)置對(duì)象居中、對(duì)齊等。 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)建文檔對(duì)象 document = Document() # 設(shè)置文檔標(biāo)題,中文要用unicode字符串 document.add_heading(u'我的一個(gè)新文檔',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 # 添加一級(jí)標(biāo)題 document.add_heading(u'一級(jí)標(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) # 獲取第一行的單元格列表對(duì)象 hdr_cells = table.rows[0].cells # 為每一個(gè)單元格賦值 # 注:值都要為字符串類型 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' # 添加分頁(yè)符 document.add_page_break() # 往新的一頁(yè)中添加段落 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)建一個(gè)空白文檔 document.styles['Normal'].font.name = '宋體' # 設(shè)置西文字體 document.styles['Normal']._element.rPr.rFonts.set(qn('w:eastAsia'), '宋體') # 設(shè)置中文字體 p = document.add_paragraph() # 添加一個(gè)段落 p.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.JUSTIFY # 設(shè)置對(duì)齊方式 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') # 延長(zhǎng)段落 run.font.color.rgb = RGBColor(255, 0, 0) # 設(shè)置字體顏色 run.font.size = Pt(22) # 設(shè)置字號(hào) run.font.bold = True # 設(shè)置下劃線
八,docx模塊其它常用方法
字號(hào)與磅值的關(guān)系
字號(hào) | 磅值 |
---|---|
八號(hào) | 5 |
七號(hào) | 5.5 |
小六 | 6.5 |
六號(hào) | 7.5 |
小五 | 9 |
五號(hào) | 10.5 |
小四 | 12 |
四號(hào) | 14 |
小三 | 15 |
三號(hào) | 16 |
小二 | 18 |
二號(hào) | 22 |
小一 | 24 |
一號(hào) | 26 |
小初 | 36 |
初號(hào) | 42 |
新增頁(yè)眉
section=document.sections[0] header=section.header bt1=header.paragraphs[0] bt1.text='此處是頁(yè)眉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)題級(jí)別1-9
h2=document.add_heading('此處默認(rèn)標(biāo)題1') h3=document.add_heading('此處添加標(biāo)題2',level=2) h4=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 | 文本以凸出頁(yè)面的方式出現(xiàn) |
hidden | 隱藏 |
imprint | 印記 |
italic | 斜體 |
name | 字體 |
no_proof | 不驗(yàn)證語(yǔ)法錯(cuò)誤 |
outline | 顯示字符的輪廓 |
shadow | 陰影 |
small_caps | 小型大寫字母 |
snap_to_grid | 定義文檔網(wǎng)格時(shí)對(duì)齊網(wǎng)絡(luò) |
strike | 刪除線 |
subscript | 下標(biāo) |
superscript | 上標(biāo) |
underline | 下劃線 |
設(shè)置居中、左右對(duì)齊、縮進(jìn)、制表符
p4=document.add_paragraph('準(zhǔn)備開始設(shè)置居中、左右對(duì)齊、縮進(jìn)等') p4.paragraph_format.alignment=WD_ALIGN_PARAGRAPH.CENTER
方法 | 作用 |
---|---|
LEFT | 左對(duì)齊 |
CENTER | 文字居中 |
RIGHT | 右對(duì)齊 |
JUSTIFY | 本兩端對(duì)齊 |
設(shè)置縮進(jìn)
默認(rèn)Inches(0.5)等于四個(gè)空格
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í),設(shè)置值單位是磅,用Pt;當(dāng)行間距為多倍行距時(shí),設(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
分頁(yè)屬性
p5.paragraph_format.keep_with_next = True
方法 | 作用 | 說明 |
---|---|---|
widow_control | 孤行控制 | 防止在頁(yè)面頂端單獨(dú)打印段落末行或在頁(yè)面底端單獨(dú)打印段落首行 |
keep_with_next | 與下段同頁(yè) | 防止在選中段落與后面一段間插入分頁(yè)符 |
page_break_before | 段前分頁(yè) | 在選中段落前插入分頁(yè)符 |
keep_together | 段中不分頁(yè) | 防止在段落中出現(xiàn)分頁(yè)符 |
添加分頁(yè)符
document.add_page_break() p5=document.add_paragraph('.add_page_break()硬分頁(yè),即使文本未滿')
添加表格、設(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ù)')
添加另一個(gè)表格 及 指定表格樣式
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') )
為每個(gè)項(xiàng)目添加數(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))
若同時(shí)定義寬度和高度,則圖片會(huì)被拉伸或壓縮到指定大??;若僅定義寬度或高度,則圖會(huì)自適應(yīng)調(diào)整大小。
保存文檔
document.save('test.docx')
上述內(nèi)容就是怎么在python中使用docx模塊讀寫docx文件,你們學(xué)到知識(shí)或技能了嗎?如果還想學(xué)到更多技能或者豐富自己的知識(shí)儲(chǔ)備,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道。
網(wǎng)站名稱:怎么在python中使用docx模塊讀寫docx文件-創(chuàng)新互聯(lián)
瀏覽地址:http://www.rwnh.cn/article6/copeog.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供搜索引擎優(yōu)化、Google、營(yíng)銷型網(wǎng)站建設(shè)、網(wǎng)站導(dǎo)航、網(wǎng)站營(yíng)銷、網(wǎng)站設(shè)計(jì)公司
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容