溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

怎么在python中使用docx模塊讀寫docx文件

發(fā)布時間:2021-03-18 16:39:24 來源:億速云 閱讀:579 作者:Leah 欄目:開發(fā)技術(shù)

本篇文章為大家展示了怎么在python中使用docx模塊讀寫docx文件,內(nèi)容簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細介紹希望你能有所收獲。

一,docx模塊

Python可以利用python-docx模塊處理word文檔,處理方式是面向?qū)ο蟮?。也就是說python-docx模塊會把word文檔,文檔中的段落、文本、字體等都看做對象,對對象進行處理就是對word文檔的內(nèi)容處理。

二,相關(guān)概念

如果需要讀取word文檔中的文字(一般來說,程序也只需要認識word文檔中的文字信息),需要先了解python-docx模塊的幾個概念。

1,Document對象,表示一個word文檔。

2,Paragraph對象,表示word文檔中的一個段落

3,Paragraph對象的text屬性,表示段落中的文本內(nèi)容。

三,模塊的安裝和導入

需要注意,python-docx模塊安裝需要在cmd命令行中輸入pip install python-docx,如下圖表示安裝成功(最后那句英文Successfully installed,成功地安裝完成)

注意在導入模塊時,用的是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è)置像素、縮進等
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è)置文檔標題,中文要用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
 
 # 添加一級標題
 document.add_heading(u'一級標題, 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'

添加標題 可設(shè)置標題級別1-9

h2=document.add_heading('此處默認標題1')
h3=document.add_heading('此處添加標題2',level=2)
h4=document.add_heading('此處添加標題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是否為“復雜代碼”
cs_bold“復雜代碼”加粗
cs_italic“復雜代碼”斜體
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下標
superscript上標
underline下劃線

設(shè)置居中、左右對齊、縮進、制表符

p4=document.add_paragraph('準備開始設(shè)置居中、左右對齊、縮進等')
p4.paragraph_format.alignment=WD_ALIGN_PARAGRAPH.CENTER
方法作用
LEFT左對齊
CENTER文字居中
RIGHT右對齊
JUSTIFY本兩端對齊

設(shè)置縮進

默認Inches(0.5)等于四個空格

p5=document.add_paragraph('content')
p5.paragraph_format.left_indent=Inches(0.5)

設(shè)置首行縮進

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è)置段落行距當行距為最小值和固定值時,設(shè)置值單位是磅,用Pt;當行間距為多倍行距時,設(shè)置值為數(shù)值。

p5.paragraph_format.line_spacing=Pt(30)
方法作用
SINGLE單倍行距(默認)
ONE_POINT_FIVE1.5倍行距
DOUBLE2倍行距
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è)置表格樣式

填充 標題行

heading_cells=table1.rows[0].cells #獲取 行列標
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')

上述內(nèi)容就是怎么在python中使用docx模塊讀寫docx文件,你們學到知識或技能了嗎?如果還想學到更多技能或者豐富自己的知識儲備,歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI