python-docx操作word文檔


參考博主:https://blog.csdn.net/zhouz92

下載模塊

1.正常安裝
pip install python-docx

2.相信這一步大家都沒問題,部分環境可能會有不能使用pip的情況,也可以使用easy_install或者源碼來進行安裝:
easy_install python-docx

3.源碼安裝
tar xvzf python-docx-{version}.tar.gz
cd python-docx-{version}
python setup.py install

4.其他安裝方式
另外附上一個下載鏈接:
https://files.pythonhosted.org/packages/4a/8e/5a01644697b03016de339ef444cfff28367f92984dc74eddaab1ed60eada/docx-0.2.4.tar.gz
Linux用戶可以使用wget來下載。windows用戶可以打開瀏覽器,輸入地址,使用瀏覽器下載。不建議使用迅雷等工具。

如果您具備一定的英語水平,可以直接閱讀官方的用戶手冊,地址如下:

https://python-docx.readthedocs.io/en/latest/#   
View Code

全局設置

import docx
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.oxml.ns import qn
from docx.shared import Cm, Pt

document = Document()
# 設置一個空白樣式
style = document.styles['Normal']
# 設置西文字體
style.font.name = 'Times New Roman'
# 設置中文字體
style.element.rPr.rFonts.set(qn('w:eastAsia'), '微軟雅黑')

一 標題操作

1.標題寫操作

from docx import Document
from docx.shared import Inches
#樣式
from docx.enum.text import WD_ALIGN_PARAGRAPH

#1.創建 Document 對象,相當於打開一個 word 文檔
document = Document()

#2.添加標題:add_heading(text="",level=1),text:標題內容 level:標題級別范圍0-9
# t1 = document.add_heading(text='這是一級標題', level=1)
# t2 = document.add_heading(text='這是二級標題', level=2)
.....
# t9 = document.add_heading(text='這是九級標題', level=9)
# t10 = document.add_heading(text='這是九級標題', level=10) #報錯:ValueError: level must be in range 0-9, got 10

#3.樣式:居中
title_obj = document.add_heading(text='這是文檔標題', level=0)
title_obj.alignment = WD_ALIGN_PARAGRAPH.CENTER #居中默認帶下划線

#4.生成文件
document.save("1-使用標題.docx") #文件路徑

2.標題讀

3.標題樣式

# 設置標題
title_ = document.add_heading(level=0)
# 標題居中
title_.alignment = WD_ALIGN_PARAGRAPH.CENTER
# 添加或追加標題內容
title_run = title_.add_run("title")
# 設置標題字體大小
title_run.font.size = Pt(14)
# 設置標題西文字體
title_run.font.name = 'Times New Roman'
# 設置標題中文字體
title_run.element.rPr.rFonts.set(qn('w:eastAsia'), '微軟雅黑')

 二 段落操作

1.段落寫

import docx
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.oxml.ns import qn
from docx.shared import Cm, Pt
#1.添加段落add_paragraph(text,style):text內容 style樣式#\n換行符,\空格符
document = Document()
p1 = document.add_paragraph(text="這只是\n段落\t而已1")
print(paragraph1.text) #段部落內容

#2.追加段落:add_run(self, text=None, style=None)
p1.add_run(text="段落2追加的內容")

#3.指定插入段落:某個段落之前插入落:insert_paragraph_before(self, text=None, style=None)
p2 = p1.insert_paragraph_before('這是段落1之前插入的新段落')

#4.刪除段落clear():將段落刪除,並返回改段內容,但是格式和樣式會保留
delete_p1 = p1.clear().text  #""
print(11,(delete_content,1),type(delete_content)#<docx.text.paragraph.Paragraph object at 0x00000204EAF04970> <class 'docx.text.paragraph.Paragraph'>

#5.保存
document.save("1-使用標題.docx") #文件路徑

2.段落讀

#1.獲取Word文檔所有段落對象:列表
paragraphs = doc.paragraphs
print(len(paragraphs),paragraphs)
# 注意:
# paragraphs 獲取的是文檔中所有段落對象的列表,嚴格來說是word文檔中正文部分的段落對象列表。因為通過前文的介紹,許多除正文部分,如 表格,頁面頁腳等元素也包含 paragraph 對象。
# 而 doc.paragraphs 獲取到的 paragraph 不包含這些段落對象。

#2.獲取段落對象:索引0,默認是文檔標題
par0 = paragraphs[0]
print(par0)
#3.獲取段落文字
par0_string = par0.text
print(par0_string)
#獲取所有段落文字信息
pars_string = [par.text for par in paragraphs]
print(pars_string)

#4.獲取段落格式
print('段落對齊方式:',par0.paragraph_format.alignment)
# 段落對齊方式: LEFT (0)
print('左縮進:',par0.paragraph_format.left_indent)
# 左縮進: None
print('右縮進:',par0.paragraph_format.right_indent)
# 右縮進: None
print('首行縮進:',par0.paragraph_format.first_line_indent)
# 首行縮進: 304800
print('行間距:',par0.paragraph_format.line_spacing)
# 行間距: 1.5
print('段前間距:',par0.paragraph_format.space_before)
# 段前間距: 198120
print('段后間距:',par0.paragraph_format.space_after)

段落文字

# 1.獲取段落的 run 對象列表
par1 = paragraphs[1]
runs = par1.runs#獲取 runs列表
print(runs,len(runs))
# 獲取run對象
run_0 = runs[0]
print(run_0.text) # 獲取 run 對象文字信息

# 獲取文字格式信息
print('字體名稱:',run_0.font.name,par1.style.font.name) #分別獲取段落和run對象字體名稱,下同理
# 字體名稱: 宋體
print('字體大小:',run_0.font.size)
# 字體大小: 152400
print('是否加粗:',run_0.font.bold)
# 是否加粗: None
print('是否斜體:',run_0.font.italic)
# 是否斜體: True
print('字體顏色:',run_0.font.color.rgb)
# 字體顏色: FF0000
print('字體高亮:',run_0.font.highlight_color)
# 字體高亮: YELLOW (7)
print('下划線:',run_0.font.underline)
# 下划線: True
print('刪除線:',run_0.font.strike)
# 刪除線: None
print('雙刪除線:',run_0.font.double_strike)
# 雙刪除線: None
print('下標:',run_0.font.subscript)
# 下標: None
print('上標:',run_0.font.superscript)

3.段落樣式

 
         
from docx import Document
from docx.shared import Inches
#樣式
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.shared import Cm, Pt
from docx.oxml.ns import qn
##字體顏色
from docx.shared import RGBColor

document=Document( )
#添加段落
# paragraph=document.add_paragraph().add_run('this is test for left_indent with inches.111111111111111111111111111111111111111111111111111111111111111111111111111')
paragraph=document.add_paragraph('this is test for left_indent with inches')
#獲取段落樣式
paragraph_format=paragraph.paragraph_format
#1.段落整體縮進
# paragraph_format.left_indent=Inches(0.3) #調整左縮進0.3英寸
#paragraph_format.right_indent = Pt(20) #設置段落從右開始縮進,使用Pt來衡量

#2.首行縮進0.74厘米,即2個字符
paragraph_format.first_line_indent = Cm(0.74)
paragraph_format.alignment=WD_ALIGN_PARAGRAPH.CENTER #內容居中

#4.行間距
#設置與上一段間隔 Pt(5)
# paragraph.space_after = Pt(20)
#設置與下一段間隔 Pt(10)
# paragraph.space_before = Pt(10)

#5.字體操作
add_run1 = paragraph.add_run("追加段落") #追加段落

# paragraph.style.font.bold = True #整體段落加粗
add_run1.font.bold = True #追加段落加粗

# paragraph.style.font.italic = True #整體斜體
add_run1.font.italic = True #追加斜體

# paragraph.style.font.underline = True #整體下划線
add_run1.font.underline = True #追加內容下划線

# add_run1.font.color.rgb=RGBColor(0x42, 0x24 , 0xE9) #追加內容顏色
paragraph.style.font.color.rgb=RGBColor(0x42, 0x24 , 0xE9) #整體內容顏色

#字體大小
paragraph.style.font.size = Pt(20)
add_run1.font.size = Pt(20)

#字體樣式
#設置西文字體
paragraph.style.font.name = '仿宋'
# add_run1.font.name = '仿宋'
# 設置中文字體
# paragraph.style.element.rPr.rFonts.set(qn('w:eastAsia'), '微軟雅黑')

#6.設置段落內部文字在遇到需分頁情況時處理狀態
  par2.paragraph_format.keep_together = True # 段中不分頁
  par2.paragraph_format.keep_with_next = True # 與下段同頁
  par2.paragraph_format.page_break_before = True # 段前分頁
  par2.paragraph_format.widow_control = True # 孤行控制

document.save('段落.docx')

三 表格

1.寫

from docx import Document
from docx.shared import Inches
#樣式
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.shared import Cm, Pt
from docx.oxml.ns import qn
##字體顏色
from docx.shared import RGBColor
#5.操作表格

document=Document(  )
"""
在Word中使用表格是一個比較復雜的內容。這一點與使用Python操作Excel相差不大,本節不會涉及太多與樣式有關的內容,關於樣式會在《在word文檔中使用樣式》使用樣式一節中做詳述的說明。
如果想要熟練使用python-docx操作Word文檔,需要認識Table()、_Cell()、 _Row()、 _Rows() _Column() 和 _Columns()五個類。
在Word文檔中添加表格需要使用Document()對象的add_table()方法。
"""
#1。創建表格:add_table(rows, cols, style=None) add_table()方法會返回一個Table對象。rows代表行數,cols代表列數,style代表樣式。
table_obj = document.add_table(3, 3,style='Table Grid')

# """
# Table()對象中報了對表格進行操作的方法和屬性,如下:
# add_column(width):如果你想添加列,可以使用此方法,使用此方法需要設置列寬
# add_row():如果你想添加行,可以添加此方法
# cell(row_idx, col_idx):如果你想訪問單個單元格,可以使用此方法
# row_cells(row_idx):返回一個序列,序列包含的是行號為row_idx的行內所有單元格
# column_cells(column_idx):返回一個序列,序列包含的是列號為column_idx的列內所有單元格
# rows:返回的是_Rows對象,是一個包含了所有行(_Row對象)的列表
# columns:返回的是_Columns對象,是一個包含了所有列(_Column對象)的列表
# """
#2.添加列
# table_obj.add_column(3)
#3.添加行
# table_obj.add_row()
#4.單個單元格操作
# """
# cell()方法實際上是返回了一個_Cell()對象。_Cell()對象代表的是一個具體的單元格,包含了操作一個單個單元格的方法與屬性,如下:
# add_paragraph(text=u'', style=None):在單元格內添加段落。
# add_table(rows, cols):在單元格中添加表格
# merge(other_cell):合並單元格
# """
#4.1選取某一單元格
cell_obj = table_obj.cell(1,1)
print(cell_obj) #<docx.table._Cell object at 0x000001AD64AE0910>
#4.2添加段落
cell_obj.add_paragraph(text='11', style=None)
print(1,cell_obj.text,9)
#刪除段落
table_obj.cell(1, 1).text = ''
print(2,cell_obj.text,10) #"11"
#4。3表格添加內容
paragraph = table_obj.cell(0, 1).text='33'
print(3, table_obj.cell(0, 1).text) #"33"
#刪除單元格數據
paragraph = table_obj.cell(0, 1).text=''
print(4, table_obj.cell(0, 1).text) #"33"
#4.4合並單元格
# table_obj.cell(0,0).merge(table_obj.cell(2,2))
c2 =cell_obj.merge(table_obj.cell(2,2))
c2.add_paragraph(text='22', style=None)

# 5.3 行與列操作:rows,columns
"""
1.
rows:返回的是_Rows對象,是一個包含了所有行(_Row對象)的列表
columns:返回的是_Columns對象,是一個包含了所有列(_Column對象)的列表
2.方法
這時它的元素是表格中的每一行/列。_Rows/_Columns對象中包含了一個屬性,如下:

table:用來返回它所屬的列表
_Row對象代表是表格中的行,具有如下屬性:

cells:即這一行所有的單元格,是個列表
height:行高
height_rule:行高規則,如果沒有設置,則默認沒有
table:用來返回它所屬的列表
_Column對象代表的是表格中的列,具有如下屬性:

cells:即這一列所有的單元格,是個列表
table:用來返回它所屬的列表
width:列寬
"""
#1.獲取行與列
row_ls = table_obj.rows

document.save('表格.docx')

# 獲取文檔中表格信息
tables = doc.tables # 獲取文檔中所有表格對象的列表
print(tables)
# [<docx.table.Table object at 0x000001957059CD48>]
print(len(tables)) # 查看文檔中表格數量
# 1
table0 = tables[0]  # 獲取表格對象

# 獲取表格的樣式信息
print(table0.style)
# _TableStyle('Normal Table') id: 190621384

# 獲取一個表格的所有單元格
cells = table0._cells
print(len(cells)) # 表格中單元格數量
# 15

# 獲取單元格內所有文字信息
cells_string = [cell.text for cell in cells]
print(cells_string)


# 獲取表格對象行數量、列數量
col_num = len(table0.columns)
print(col_num) # 3
# 行數量
row_num = len(table0.rows)
print(row_num) # 5

# 獲取行對象
row0 = table0.rows[0]
# 獲取列對象
col0 = table0.columns[0]

# 獲取行對象文字信息
'要用 row0.cells 獲取行對象的 cell 才能獲取其文字信息'
row0_string = [cell.text for cell in row0.cells]
print(row0_string)

# 獲取列對象文字信息
col0_string = [cell.text for cell in col0.cells]
print(col0_string)

四 圖片

1.寫

from docx import Document,shared
from docx.shared import Inches
#樣式
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.shared import Cm, Pt
from docx.oxml.ns import qn
##字體顏色
from docx.shared import RGBColor

document = Document()

#1.添加圖片:add_picture(self, image_path_or_stream, width=None, height=None)
# 在文檔中增加圖片,並對設置圖片大小,當只設置一個方向的長度(寬或高)時,另一方向會自動縮放.
document.add_picture('編程雜藝.png',width=shared.Inches(1))  # 按英寸設置
document.add_picture('編程雜藝.png',height=shared.Cm(2))  # 按厘米設置


#4.生成文件
document.save("1-使用圖片.docx") #文件路徑

四 章節頁眉頁腳

1.新建章節

sec = document.sections
print(sec) # <docx.section.Sections object at 0x000000000B312E88>
print(len(sec)) # 1

# 新建一個章節
document.add_section()
print(len(sec)) # 2

2.獲取文檔頁面邊距:word 文檔的頁邊距、頁眉頁腳的設置和章節對象有關:

 
         
from docx import Document
#1.讀取文檔
doc = Document('1-使用頁.docx')
#2. 獲取文檔所有章節:列表
sections = doc.sections
print(sections)# <docx.section.Sections object at 0x000000000B2E1148>
# 查看章節數量
print(len(sections)) # 2
#3.獲取單個章節
sec0 = sections[0]
# 獲取頁面邊距值:(單位為像素)
print('左邊距:',sec0.left_margin)
# 左邊距: 1143000
print('右邊距:',sec0.right_margin)
# 右邊距: 1143000
print('上邊距:',sec0.top_margin)
# 上邊距: 914400
print('下邊距:',sec0.bottom_margin)
# 下邊距: 914400
print('頁眉邊距:',sec0.header_distance)
# 頁眉邊距: 457200
print('頁腳邊距:',sec0.footer_distance)
# 頁腳邊距: 457200

3.設置文檔頁面邊距、頁面大小

# 設置頁面高度、寬度
sec0.page_height = shared.Inches(15)
sec0.page_width = shared.Inches(10)

# 也可以設置頁面的邊距:
sec0.left_margin = shared.Inches(1)
sec0.right_margin = shared.Inches(1)
sec0.top_margin = shared.Inches(2)
sec0.bottom_margin = shared.Inches(2)

4、設置頁眉頁腳和頁面方向

設置頁面頁腳時,先獲取頁眉頁腳對象:

#1. 設置頁眉
head0 = sec0.header  # 返回頁眉對象
font0 = sec0.footer  # 返回頁腳對象
print(head0)
# <docx.section._Header object at 0x000000000B312E08>
print(font0)
# <docx.section._Footer object at 0x000000000B312B88>

"在設置word文檔的頁眉頁腳時,有一個非常重要的是否與前一節相同"
# 查看頁眉是否和上節一直
print(head0.is_linked_to_previous)  # 默認為 True

# 設置頁眉
"頁眉也是一個塊級對象,里面也包含了 Paragraph 對象,"
"所以對齊方式,文字格式設置方式和前文介紹一致。"
#頁眉頁腳
sec = document.sections
sec0 = sec[0] # 獲取章節對象
head0 = sec0.header # 返回頁眉對象
font0 = sec0.footer # 返回頁腳對象

#設置頁眉
head0_par = head0.paragraphs[0]
head0_par.add_run('頁眉')

# 設置頁腳
font0_par = font0.paragraphs[0]
font0_par.add_run('頁腳')
 # 注: 設置頁腳按序列增加的方式暫未找到

# 導入設置頁面方向所需模塊
from docx.enum.section import WD_ORIENT
# 獲取章節對象
section = document.sections[0]
# 設置頁面方向
section.orientation = WD_ORIENT.LANDSCAPE # 橫向

可設置項有橫向( LANDSCAPE ) 和縱向 ( PORTRAIT )

 背景顏色設置方法: (與字體顏色設置方法有區別)

# 設置背景顏色
from  docx.enum.text import WD_COLOR_INDEX
run_2.font.highlight_color = WD_COLOR_INDEX.YELLOW

背景顏色可選值有:
'''
'AUTO', 0, 'default'
'BLACK', 1, 'black'
'BLUE', 2, 'blue'
'BRIGHT_GREEN', 4, 'green',
'DARK_BLUE', 9, 'darkBlue',
'DARK_RED', 13, 'darkRed'
'DARK_YELLOW', 14, 'darkYellow'
'GRAY_25', 16, 'lightGray'
'GRAY_50', 15, 'darkGray'
'GREEN', 11, 'darkGreen'
'PINK', 5, 'magenta'
'RED', 6, 'red'
'TEAL', 10, 'darkCyan'
'TURQUOISE', 3, 'cyan'
'VIOLET', 12, 'darkMagenta'
'WHITE', 8, 'white'
'YELLOW', 7, 'yellow'
'''

分頁

from docx import Document
document = Document()
document.add_paragraph('這是第一頁')
document.add_page_break()
document.add_paragraph('這是第二頁')
document.save("5-使用分頁.docx")

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM