电竞比分网-中国电竞赛事及体育赛事平台

分享

Python之word文件操作教程(全)

 昵稱2548375 2023-06-13 發(fā)布于河北

Python之word文件操作教程

前提: python操作word的一個常用庫:python-docx。

安裝:pip install python-docx

參考自官網(wǎng):https://python-docx./en/latest/

一、基礎介紹

1、打開/保存文檔

python-docx可以打開一個新的文檔,也可以打開一個已有的文檔并對它進行修改。

新建文檔:

from docx import Document

document = Document()  # 創(chuàng)建一個Document對象,同時也會創(chuàng)建一個空白文檔

document.save('實例.docx') # 保存文檔

打開已有文檔:

document = Document('數(shù)據(jù).docx') # 打開名為數(shù)據(jù)的word文檔

document.save('實例.docx') # 保存文檔

2、添加段落

在文檔末尾添加新段落:

paragraph = document.add_paragraph('我要學Python!')

也可以把一個段落作為 "光標",在其正上方插入一個新段落:

prior_paragraph = paragraph.insert_paragraph_before('我是劉亦菲')

這樣就可以在文檔中間插入段落了。

3、添加標題

添加方法如下:

document.add_heading('標題')

默認情況下,會添加一個頂級標題,在 Word 中顯示為“標題 1”。當你想要一個小節(jié)的標題時,只需將你想要的級別指定為 1 到 9 之間的整數(shù):

document.add_heading('標題2', level=2)

如果指定級別為0,則會添加一個【標題】段落。

4、添加分頁符

方法如下:

document.add_page_break()

5、添加表格

創(chuàng)建表格:

table = document.add_table(rows=2, cols=2)

通過行和列的索引(從零開始)來確定單元格:

cell = table.cell(0, 1)

往單元格里寫入數(shù)據(jù):

cell.text = '單元格'

如果想直接訪問一行/一列的單元格的話,可以通過表的 .rows /.columns 屬性來實現(xiàn),每行/列都有一個 .cells 屬性。

行/列上的 .cells 屬性是可迭代的,我們可以通過索引來訪問,也能直接通過for 循環(huán)來使用:

# 通過表的.rows屬性獲取第一行,通過行的.cells屬性獲取單元格

row = table.rows[0]

row.cells[0].text = '1'

row.cells[1].text = '2'

# 利用循環(huán)獲取所有單元格數(shù)據(jù)

for row in table.rows:

for cell in row.cells:

print(cell.text)

使用 len()來計算表中的行數(shù)或列數(shù):

row_count = len(table.rows)

col_count = len(table.columns)

在表的下方插入一行:

row = table.add_row()

設計表格樣式:

table.style = 'Light Shading Accent 1'

可設置的表格樣式名稱:

Table Normal

colorful Grid

colorful Grid Accent 1

colorful Grid Accent 2

colorful Grid Accent 3

colorful Grid Accent 4

colorful Grid Accent 5

colorful Grid Accent 6

colorful List

colorful List Accent 1

colorful List Accent 2

colorful List Accent 3

colorful List Accent 4

colorful List Accent 5

colorful List Accent 6

colorful Shading

colorful Shading Accent 1

colorful Shading Accent 2

colorful Shading Accent 3

colorful Shading Accent 4

colorful Shading Accent 5

colorful Shading Accent 6

Dark List

Dark List Accent 1

Dark List Accent 2

Dark List Accent 3

Dark List Accent 4

Dark List Accent 5

Dark List Accent 6

Light Grid

Light Grid Accent 1

Light Grid Accent 2

Light Grid Accent 3

Light Grid Accent 4

Light Grid Accent 5

Light Grid Accent 6

Light List

Light List Accent 1

Light List Accent 2

Light List Accent 3

Light List Accent 4

Light List Accent 5

Light List Accent 6

Light Shading

Light Shading Accent 1

Light Shading Accent 2

Light Shading Accent 3

Light Shading Accent 4

Light Shading Accent 5

Light Shading Accent 6

Medium Grid 1

Medium Grid 1 Accent 1

Medium Grid 1 Accent 2

Medium Grid 1 Accent 3

Medium Grid 1 Accent 4

Medium Grid 1 Accent 5

Medium Grid 1 Accent 6

Medium Grid 2

Medium Grid 2 Accent 1

Medium Grid 2 Accent 2

Medium Grid 2 Accent 3

Medium Grid 2 Accent 4

Medium Grid 2 Accent 5

Medium Grid 2 Accent 6

Medium Grid 3

Medium Grid 3 Accent 1

Medium Grid 3 Accent 2

Medium Grid 3 Accent 3

Medium Grid 3 Accent 4

Medium Grid 3 Accent 5

Medium Grid 3 Accent 6

Medium List 1

Medium List 1 Accent 1

Medium List 1 Accent 2

Medium List 1 Accent 3

Medium List 1 Accent 4

Medium List 1 Accent 5

Medium List 1 Accent 6

Medium List 2

Medium List 2 Accent 1

Medium List 2 Accent 2

Medium List 2 Accent 3

Medium List 2 Accent 4

Medium List 2 Accent 5

Medium List 2 Accent 6

Medium Shading 1

Medium Shading 1 Accent 1

Medium Shading 1 Accent 2

Medium Shading 1 Accent 3

Medium Shading 1 Accent 4

Medium Shading 1 Accent 5

Medium Shading 1 Accent 6

Medium Shading 2

Medium Shading 2 Accent 1

Medium shading 2 Accent 2

Medium Shading 2 Accent 3

Medium Shading 2 Accent 4

Medium Shading 2 Accent 5

Medium Shading 2 Accent 6

Table Grid

對應的word中的表格樣式:

6、添加圖片

Word可以使用【插入】-【圖片】菜單項將圖像插入到文檔中。以下是在 python-docx 中的操作方法:

document.add_picture('圖片.png')

添加的圖像默認以原始大小顯示,但是可以通過指定寬度或高度來改變其大小,單位可以選擇英寸inches 或厘米 centimeters:

from docx.shared import Inches

document.add_picture('image-filename.png', width=Inches(1.0))

如果只指定了寬度或高度的一個,python-docx 會自動計算另一個的正確縮放值。這樣就可以保留縱橫比,讓圖片不會被拉伸。

7、設置段落樣式

可以在創(chuàng)建一個段落時設置一個段落樣式:

document.add_paragraph('段落', style='List Bullet')

這兩行相當于上面的那一行:

paragraph = document.add_paragraph('段落')

paragraph.style = 'List Bullet'

可設置的段落樣式名稱:

Normal

Body Text

Body Text 2

Body Text 3

caption

Footer

Header

Heading 1

Heading 2

Heading 3

Heading 4

Heading 5

Heading 6

Heading 7

Heading 8

Heading 9

Intense Quote

List

List 2

List 3

List Bullet

List Bullet 2

List Bullet 3

List continue

List continue 2

List continue 3

List Number

List Number 2

List Number 3

List Paragraph

macro

No spacing

Quote

subtitle

TOc Heading

Title

8、首行縮進

通過設置paragraph_format.first_line_indent屬性可以設置縮進大小為當前字體大小的2倍。

9、設置粗體和斜體

段落包含了所有塊級格式,如縮進、行高、制表符等。但字符級的格式化如粗體和斜體,是在運行(run)級別應用的。

一個段落中的所有內(nèi)容都必須在一個運行中,但也可以有多個運行。

比如,一個中間有一個粗體字的段落需要三個運行:一個正常的運行;一個包含該字的粗體運行;另一個正常的運行用于粗體字后面的文字。

當通過.add_paragraph()方法添加一個段落時,它會另外運行一個段落。而使用段落上的.add_run()方法可以直接在運行中的段落后面添加內(nèi)容:

paragraph = document.add_paragraph('我是另外一個段落')

paragraph.add_run('這是直接在后面新增的內(nèi)容')

run對象的.bold和.italic屬性,可以用來設置加粗或斜體:

paragraph = document.add_paragraph('段落')

run = paragraph.add_run('加粗')

run.bold = True

paragraph.add_run('段落')

如果之后不需要對“運行”引用的話,可以直接在.add_run()的結(jié)果上設置粗體或斜體:

paragraph.add_run('加粗').bold = True

如果要從運行中建立段落的話,可以不用向.add_paragraph()提供文本:

paragraph = document.add_paragraph()

paragraph.add_run('段落')

paragraph.add_run('加粗').bold = True

paragraph.add_run('段落')

text屬性有哪些?看下表:

屬性

描述

bold

文本以粗體出現(xiàn)

italic

文本以斜體出現(xiàn)

underline

文本帶下劃線

strike

文本帶刪除線

double_strike

文本帶雙刪除線

all_caps

文本以大寫首字母出現(xiàn)

small_caps

文本以大寫首字母出現(xiàn),小寫字母小兩個點

shadow

文本帶陰影

outline

文本以輪廓線出現(xiàn),而不是實心

rtl

文本從右至左書寫

imprint

文本以刻入頁面的方式出現(xiàn)

emboss

文本以凸出頁面的方式出現(xiàn)

10、設置字符樣式

除了設置段落級別的段落樣式之外,Word還可以設置運行級別的字符樣式。字符樣式可以理解為字體,包括其字體、大小、顏色、粗體、斜體等。

可設置的字符樣式名稱:

Body Text char

Body Text 2 char

Body Text 3 char

Book Title

Default Paragraph Font

Emphasis

Heading 1 Char

Heading 2 Char

Heading 3 char

Heading 4 Char

Heading 5 Char

Heading 6 Char

Heading 7 char

Heading 8 Char

Heading 9 Char

Intense Emphasis

Intense Quote char

Intense Reference

Macro Text char

Quote Char

strong

Subtitle char

Subtle Emphasis

Subtle Reference

Title char

可以在添加新運行的時候設置字符樣式:

paragraph = document.add_paragraph('這是正常的文字,')

paragraph.add_run('這是emphasis格式文字', 'Emphasis')

也可以在創(chuàng)建運行后將樣式應用到運行:

paragraph = document.add_paragraph('這是正常的文字,')

run = paragraph.add_run('這是emphasis格式文字')

run.style = 'Emphasis'

11、實例

下面我們來看一個具體的實例鞏固一下上面的知識:

from docx import Document

from docx.shared import Inches

document = Document() # 創(chuàng)建一個Document對象,同時也會創(chuàng)建一個空白文檔

# 添加段落和標題

document.add_heading('標題', 0)

p = document.add_paragraph('一個段落里可以有')

p.add_run('粗體').bold = True

p.add_run('和')

p.add_run('斜體').italic = True

document.add_heading('標題1', level=1)

document.add_paragraph('設置Intense quote段落樣式', style='Intense Quote')

document.add_paragraph('設置成項目符號中的第一項的段落樣式', style='List Bullet')

document.add_paragraph('設置成編號里的第一項的段落樣式', style='List Number')

# 添加圖片

document.add_picture('劉亦菲.jpg', width=Inches(1.25))

# 表格數(shù)據(jù)

records = (

(1, '菲菲', '學Python'),

(2, '小紅', '唱歌'),

(3, '小蘭', '跳舞')

)

# 添加表格

table = document.add_table(rows=1, cols=3)

hdr_cells = table.rows[0].cells

hdr_cells[0].text = '編號'

hdr_cells[1].text = '姓名'

hdr_cells[2].text = '愛好'

for number, name, hobby in records:

row_cells = table.add_row().cells

row_cells[0].text = str(number)

row_cells[1].text = name

row_cells[2].text = hobby

table.style = 'Light Shading Accent 1'    # 設置表格樣式

document.add_page_break() # 添加換頁符

document.save('111.docx') #保存文件

效果:

二、段落屬性

段落有多種屬性,可以用來設置在頁面中的位置以及將其內(nèi)容劃分為單獨行的方式。

一般來說,最好定義一個段落樣式,將這些屬性收集到一個組中,并將適當?shù)臉邮綉糜诿總€段落,而不是重復地將這些屬性直接應用于每個段落。

這類似于級聯(lián)樣式表 (CSS) 如何與 HTML 一起工作。此處描述的所有段落屬性都可以使用樣式設置,也可以直接應用于段落。

段落的格式屬性是通過使用段落的paragraph_format屬性獲得的ParagraphFormat對象來訪問的。

1、對齊

可以使用WD_PARAGRAPH_ALIGNMENT 中的選項將段落的水平對齊方式設置為左對齊、居中對齊、右對齊或兩端對齊 :

from docx import Document

from docx.enum.text import WD_ALIGN_PARAGRAPH

document = Document()

paragraph = document.add_paragraph()

paragraph_format = paragraph.paragraph_format

print(paragraph_format.alignment)   # --> None:表示對齊方式是從樣式層次中繼承的

paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER

print(paragraph_format.alignment)   # --> CENTER (1)

WD_PARAGRAPH_ALIGNMENT的選項:

LEFT:左對齊

CENTER:居中對齊

RIGHT:右對齊

JUSTIFY:兩端對齊

DISTRIBUTE:段落字符分布以填充段落的整個寬度。

JUSTIFY_MED:以中等字符壓縮率對齊

JUSTIFY_HI:合理的高字符壓縮比對齊

JUSTIFY_LOW:以較低的字符壓縮率對齊

THAI_USTIFY:根據(jù)泰語格式布局對齊

2、縮進

縮進是指段落與頁邊之間的水平空間,一個段落可以在左邊和右邊分別縮進。

其中第一行可以與段落的其他部分有不同的縮進:首行縮進 first line indent(第一行縮進而其他行不縮進)、懸掛縮進hanging indent(段落的第一行不縮進但段落的其他行縮進)。

縮進是用一個長度(Length)值來指定的,常見長度(Length)值及其單位轉(zhuǎn)換:

厘米cm: 以(浮點數(shù))表示的等效長度。

英制公制emu: 以(整數(shù))表示的等效長度

英寸Inches: 以英寸(浮點數(shù))表示的等效長度。

毫米mm: 以毫米(浮點數(shù))表示的等效長度。

磅Pt: 以(浮點數(shù))表示的等效長度。

緹twips: 以(整數(shù))表示的等效長度。

1英寸= 2.54厘米=914400內(nèi)置的單位

1磅=1/72英寸

1緹=1/20磅=1/1440英寸

如果縮進是負值,會使段落與頁邊距重疊。

None的值表示縮進值是從樣式層次結(jié)構中繼承的。將None指定給一個縮進屬性,可以刪除任何直接應用的縮進設置,并恢復從樣式層次結(jié)構的繼承性。

from docx import Document

from docx.shared import Inches

document = Document()

paragraph = document.add_paragraph()

paragraph_format = paragraph.paragraph_format

print(paragraph_format.left_indent)    # --> None  指示縮進是從樣式層次結(jié)構繼承的

paragraph_format.left_indent = Inches(0.5)

print(paragraph_format.left_indent)    # --> 457200

print(paragraph_format.left_indent.inches) # --> 0.5

右側(cè)縮進的方法一樣:

from docx import Document

from docx.shared import Pt

document = Document()

paragraph = document.add_paragraph()

paragraph_format = paragraph.paragraph_format

print(paragraph_format.right_indent) # --> None

paragraph_format.right_indent = Pt(24)

print(paragraph_format.right_indent) # --> 304800

print(paragraph_format.right_indent.pt) # --> 24.0

首行的縮進使用 first_line_indent 屬性指定,如果值為正值表示首行縮進,負值則表示懸掛縮進:

from docx import Document

from docx.shared import Inches

document = Document()

paragraph_format = paragraph.paragraph_format

print(paragraph_format.first_line_indent)    # --> None

paragraph_format.first_line_indent = Inches(-0.25)

print(paragraph_format.first_line_indent)       # --> -228600

print(paragraph_format.first_line_indent.inches)       # --> -0.25

3、制表位

制表位是指在水平標尺上的位置,可以用來設置文字縮進的距離或一欄文字開始之處。

制表位的三要素包括制表位位置、制表位對齊方式和制表位的前導字符。

段落或樣式的制表位可以用paragraph_format對象的 tab_stops 屬性訪問:

paragraph_format = paragraph.paragraph_format

tab_stops = paragraph_format.tab_stops

print(tab_stops)

# -->>  

可以使用 add_tab_stop() 方法添加一個新的制表位:

paragraph_format = paragraph.paragraph_format

tab_stops = paragraph_format.tab_stops

tab_stop = tab_stops.add_tab_stop(Inches(1.5))

print(tab_stop.position)   # -->>  1371600

print(tab_stop.position.inches)   # -->>  1.5

制表位的對齊默認為左對齊,但可以通過 WD_TAB_ALIGNMENT 的選項來設置。前導字符默認為空格,可以通過 WD_TAB_LEADER的選項來設置:

from docx import Document

from docx.shared import Inches

from docx.enum.text import WD_TAB_ALIGNMENT, WD_TAB_LEADER

document = Document()

paragraph = document.add_paragraph()

paragraph_format = paragraph.paragraph_format

tab_stops = paragraph_format.tab_stops

tab_stop = tab_stops.add_tab_stop(Inches(1.5), WD_TAB_ALIGNMENT.RIGHT, WD_TAB_LEADER.DOTS)

print(tab_stop.alignment)   # -->  RIGHT (2)

print(tab_stop.leader)  # -->  DOTS (1)

document.save('實例.docx') #保存文件

WD_TAB_ALIGNMENT的選項:

LEFT:左對齊

CENTER:居中對齊

RIGHT:右對齊

DECIMAL:小數(shù)點對齊

BAR:豎線對齊

LIST:列表對齊(不推薦)

CLEAR:清除繼承的制表位

END:類似于右對齊(不推薦)

NUM:類似于左對齊(不推薦)

START:類似于左對齊(不推薦)

WD_TAB_LEADER的選項:

SPACES:空格,默認

DOTS:點

DASHES:短劃線

LINES:雙下劃線

HEAVY:粗線

MIDDLE_DOT:小黑點

可以使用序列TabStops 上的索引訪問現(xiàn)有的制表位:

tab_stops[0]   # -->  

4、段落間距 

可以通過space_before屬性來控制段落前的間距,通過space_after 屬性來控制段落后的間距。

在頁面排版過程中,段落間的間距是被折疊的,這意味著兩個段落之間的間距是第一段的斷后距和第二段的斷前距的最大值。

段落間距設置為長度值,通常使用 Pt(磅):

from docx import Document

from docx.shared import Pt

document = Document()

paragraph = document.add_paragraph()

paragraph_format = paragraph.paragraph_format

print(paragraph_format.space_before, paragraph_format.space_after)  # -->>  None None

paragraph_format.space_before = Pt(18)

print(paragraph_format.space_before.pt)  # -->>  18.0

paragraph_format.space_after = Pt(12)

print(paragraph_format.space_after.pt)  # -->>  12.0

5、行間距

行間距是段落中每行之間的距離,行距可以指定為絕對距離或相對于行高(本質(zhì)上是所用字體的磅值)。

典型的絕對距離是18磅,典型的相對行高是2倍行距(2.0行高),默認的行距是單倍行距(1.0行高)。

行間距由 line_spacing 和 line_spacing_rule 屬性的交互控制。

line_spacing 可以是長度值、(?。└↑c數(shù)或無:長度值表示絕對距離;浮點數(shù)表示行高數(shù);None 表示行距是繼承的。

line_spacing_rule 是 WD_LINE_SPACING的選項或None。

from docx import Document

from docx.shared import Length

from docx.shared import Pt

document = Document()

paragraph = document.add_paragraph()

paragraph_format = paragraph.paragraph_format

print(paragraph_format.line_spacing)    # >>> None

print(paragraph_format.line_spacing_rule)    # >>> None

paragraph_format.line_spacing = Pt(18)

print(isinstance(paragraph_format.line_spacing, Length))    # >>> True

print(paragraph_format.line_spacing.pt)    # >>> 18.0

print(paragraph_format.line_spacing_rule)    # >>> EXACTLY (4)

paragraph_format.line_spacing = 1.75

print(paragraph_format.line_spacing)    # >>> 1.75

print(paragraph_format.line_spacing_rule)    # >>> MULTIPLE (5)

WD_LINE_SPACING的選項:

ONE_POINT_FIVE: 1.5倍行距

AT_LEAST: 最小值

DOUBLE: 2倍行距

EXACTLY: 固定值

MULTIPLE: 多倍行距

SINGLE: 單倍行距(默認)

6、分頁

有四個段落屬性:keep_together、keep_with_next、page_break_before 和 widow_control 可以設置分頁。

段中不分頁keep_together:在頁面或列中將段落行放在一起。

與下段同頁keep_with_next:在頁面上或列中將段落放在一起。

段前分頁 page_break_before:始終在段落前強制分頁符。

孤行控制 widow_control:控制段落上的孤行和孤立行。

這四個屬性都是三態(tài)的,即可以取值 True、False 或 None。

None 表示屬性值是從樣式層次結(jié)構繼承的;True 表示該屬性“開啟”;False 表示該屬性“關閉”。

print(paragraph_format.keep_together)    # >>> None

paragraph_format.keep_with_next = True

print(paragraph_format.keep_with_next)    # >>> True

paragraph_format.page_break_before = False

print(paragraph_format.page_break_before)    # >>> False

三、設置字符格式

字符格式應用于運行級別,字符格式包括字體和大小、粗體、斜體和下劃線。

可以像這樣訪問運行的字體:

from docx import Document

document = Document()

run = document.add_paragraph().add_run()

font = run.font

字符、段落和表格樣式也可以指定字符格式,以應用于具有該樣式的內(nèi)容。比如可以像這樣訪問樣式的字體:

from docx import Document

document = Document()

style = document.styles['Normal']

font = style.font

字體和大小設置:

from docx.shared import Pt

font.name = 'Calibri'

font.size = Pt(12)

字體的許多屬性(如粗體、斜體、全大寫、刪除線、上標)也是三態(tài)的,可以采用值 True、False 和 None。

font.bold, font.italic # >>> None None

font.italic = True

font.italic  # >>> True

font.italic = False

font.italic # >>> False

font.italic = None

font.italic # >>> None

1、下劃線

下劃線是一種特殊的情況。它是三態(tài)屬性和枚舉值屬性的混合體。 

True 表示單下劃線,是最常見的, False 表示沒有下劃線。如果不需要下劃線的話一般設置 None。

其他形式的下劃線,例如雙線或虛線,是使用 WD_UNDERLINE的選項指定的:

font.underlinec # >>> None

font.underline = True

font.underline = WD_UNDERLINE.DOT_DASH

WD_UNDERLINE的選項:

NONE:無下劃線

SINGLE:單下劃線

WORDS:字下加線

DOUBLE:雙下劃線

DOTTED:點式下劃線

THICK:粗線

DASH:虛下劃線

DOT_DASH:點-短線下劃線

DOT_DOT_DASH:點-點-短線下劃線

WAVY:波浪線

DOTTED_HEAVY:粗點式下劃線

DASH_HEAVY:粗虛下劃線

DOT_DASH_HEAVY:粗點-粗短線下劃線

DOT_DOT_DASH_HEAVY:粗點-粗點-粗短線下劃線

WAVY_HEAVY:粗波浪線

DASH_LONG:長虛下劃線

WAVY_DOUBLE:雙波浪線

DASH_LONG_HEAVY:長粗虛下劃線

2、字體顏色

每個 Font 對象都有一個 ColorFormat 對象,該對象可以設置字體顏色。

將特定的 RGB 顏色應用于字體:

from docx.shared import RGBColor

font.color.rgb = RGBColor(0x42, 0x24, 0xE9)

通過MSO_THEME_COLOR_INDEX的選項可以將一個字體設置為主題顏色:

from docx.enum.dml import MSO_THEME_COLOR

font.color.theme_color = MSO_THEME_COLOR.ACCENT_1

MSO_THEME_COLOR_INDEX選項:

NOT_THEME_COLOR: 非主題顏色

ACCENT_1: ACCENT 1主題顏色

ACCENT_2: ACCENT 2主題顏色

ACCENT_3: ACCENT 3主題顏色

ACCENT_4: ACCENT 4主題顏色

ACCENT_5: ACCENT 5主題顏色

ACCENT_6: ACCENT 6主題顏色

BACKGROUND_1: 背景1主題顏色

BACKGROUND_2: 背景2主題顏色

DARK_1: 深色1主題顏色

DARK_2: 深色2主題顏色

FOLLOWED_HYPERLINK: 已單擊超鏈接的主題顏色

HYPERLINK: 超鏈接的主題顏色

LIGHT_1: 淺色1主題顏色

LIGHT_2: 淺色2主題顏色

TEXT_1: 文本1 主題顏色

TEXT_2: 文本2主題顏色

MIXED: 多種主題顏色混合

通過將 None 分配給 ColorFormat 的 rgb 或 theme_color 屬性,可以將字體的顏色恢復為其默認(繼承)值:

font.color.rgb = None

確定字體的顏色首先要確定其顏色類型:

font.color.type

type 屬性的值可以是 MSO_COLOR_TYPE 的選項或 None。

MSO_COLOR_TYPE.RGB 表示它是 RGB 顏色。

MSO_COLOR_TYPE.THEME 表示主題顏色。

MSO_COLOR_TYPE.AUTO 表示其值由應用程序自動確定,通常設置為黑色。

None 表示不應用顏色,顏色繼承自樣式層次;這是最常見的情況。

四、設置節(jié)

Word 支持節(jié)的概念,即具有相同頁面布局設置(如頁邊距和頁面方向)的文檔的一個分區(qū)。

這就是為什么一個文檔可以包含一些縱向布局的頁面的同時包含其他橫向布局的頁面。

大多數(shù) Word 文檔默認只有一個節(jié),而且大多數(shù)文檔沒有理由更改默認邊距或其他頁面布局。但是想更改頁面布局時,需要了解節(jié)才能完成它。

1、訪問節(jié)

Document 對象上的sections 屬性提供對文檔節(jié)的訪問:

from docx import Document

document = Document()

sections = document.sections

print(sections) # >>>  

print(len(sections)) # >>>1

section = sections[0]

print(section) # >>>  

for section in sections:

print(section.start_type)   # >>>  NEW_PAGE (2)

2、添加新節(jié)

Document.add_section() 方法可以在文檔末尾開始一個新節(jié)。調(diào)用此方法后添加的段落和表格將出現(xiàn)在新的節(jié)中:

from docx import Document

from docx.enum.section import WD_SECTION

document = Document()

current_section = document.sections[-1]  # 文檔的最后一節(jié)

print(current_section.start_type)# >>> NEW_PAGE (2)

new_section = document.add_section(WD_SECTION.ODD_PAGE)

print(new_section.start_type) # >>> ODD_PAGE (4)

3、節(jié)屬性

Section 對象有 11 個屬性,可以查找和設置頁面布局。

1)節(jié)開始類型

Section.start_type 描述了節(jié)的起始位置:

from docx import Document

from docx.enum.section import WD_SECTION

document = Document()

section = document.sections[-1]

print(section.start_type)   #>>> NEW_PAGE (2)

section.start_type = WD_SECTION.ODD_PAGE

print(section.start_type)   #>>> ODD_PAGE (4)

start_type 的值是 WD_SECTION_START 中的選項:

實例:

from docx.enum. section import WD_SECTION

section = document.sections [0]

section.start_type = WD_SECTION.NEW_PAGE

可選項:

CONTINUOUS:接續(xù)本頁

NEW_COLUMN:新建欄

NEW_PAGE:新建頁

EVEN_PAGE:偶數(shù)頁

ODD_PAGE:奇數(shù)頁

2)頁面尺寸和方向

Section 上有三個屬性可以設置頁面的尺寸和方向,三個可以一起使用,例如,將節(jié)的方向從縱向更改為橫向:

from docx import Document

from docx.enum.section import WD_ORIENT

document = Document()

section = document.sections[-1]

print(section.orientation, section.page_width, section.page_height)    

#-->> PORTRAIT (0) 7772400 10058400

new_width, new_height = section.page_height, section.page_width

section.orientation = WD_ORIENT.LANDSCAPE

section.page_width = new_width

section.page_height = new_height

print(section.orientation, section.page_width, section.page_height)

#-->> LANDSCAPE (1) 10058400 7772400

3)頁邊距

Section上有七個屬性可以設置文本在頁面上出現(xiàn)位置的各種邊緣間距。

from docx import Document

from docx.enum.section import WD_ORIENT

from docx.shared import Inches

document = Document()

section = document.sections[-1]

print(section.left_margin, section.right_margin)  

#--> 1143000 1143000

print(section.top_margin, section.bottom_margin)  

#--> 914400 914400  

print(section.gutter)  #--> 0

print(section.header_distance, section.footer_distance)  

#--> 457200 457200

section.left_margin = Inches(1.5)

section.right_margin = Inches(1)

print(section.left_margin, section.right_margin)  

#--> 1371600 914400

五、設置頁眉和頁腳

Word 支持頁眉header和頁腳footer。

頁眉是出現(xiàn)在每頁上邊距區(qū)域的文本,與文本主體分開,通常傳達上下文信息,例如文檔標題、作者、創(chuàng)建日期或頁碼。

文檔中的頁眉在不同的頁面之間是相同的,只有很小的內(nèi)容差異,例如節(jié)標題或頁碼的變化。頁眉也稱為運行頭。

頁腳在各方面都類似于頁眉,只是它出現(xiàn)在頁面底部。

1、訪問節(jié)的頁眉/頁腳

頁眉header 和頁腳footer是鏈接到節(jié)的,這就允許每個節(jié)可以有不同的頁眉和/頁腳。例如,橫向部分的頁眉可能比縱向部分更寬。

每個節(jié)對象都有一個 .header/.footer 屬性,提供對該部分的 _Header /_Footer對象的訪問:

from docx import Document

document = Document()

section = document.sections[0]

header = section.header

print(header)

#-->  

footer = section.footer

print(footer)

#-->  

_Header /_Footer對象始終存在于 section.header/ section.footer上,即使沒有為該節(jié)定義頁眉/頁腳。

_Header.is_linked_to_previous / _Footer.is_linked_to_previous表示存在實際的頁眉/頁腳定義:

print(header.is_linked_to_previous) #-->True

print(footer.is_linked_to_previous) #-->True

新文檔沒有頁眉/頁腳(在它包含的單個節(jié)上),因此 .is_linked_to_previous 在這種情況下為 True。

2、添加頁眉/頁腳

只需編輯 _Header  / _Footer 對象的內(nèi)容,就可以將頁眉/頁腳添加到新文檔中。

_Header  / _Footer 對象的內(nèi)容和Document 對象一樣可以進行編輯。請注意,與新文檔一樣,新頁眉/頁腳已經(jīng)包含一個(空)段落:

from docx import Document

document = Document()

section = document.sections[0]

header = section.header

paragraph = header.paragraphs[0]

paragraph.text = "頁眉內(nèi)容"

footer = section.footer

paragraph = footer.paragraphs[0]

paragraph.text = "頁腳內(nèi)容"

document.save('實例.docx') #保存文件

效果:

另外注意,添加內(nèi)容(甚至只是訪問 header.paragraphs/footer.paragraphs)的行為添加了頁眉/頁腳定義并更改了 .is_linked_to_previous 的狀態(tài):

print(header.is_linked_to_previous)   # >>> False

print(footer.is_linked_to_previous)   # >>> False

3、添加分區(qū)頁眉/頁腳內(nèi)容

一個具有多個區(qū)域的頁眉通常是通過精心放置的制表符來完成的。居中和右對齊的 區(qū)域所需的制表符是Word中頁眉和頁腳樣式的一部分。

插入的制表符 ("\t") 用于分隔左對齊、居中和右對齊的頁眉/頁腳內(nèi)容:

from docx import Document

document = Document()

section = document.sections[0]

header = section.header

paragraph = header.paragraphs[0]

paragraph.text = "居左頁眉\t居中頁眉\t居右頁眉"

paragraph.style = document.styles["Header"] # 可省略

footer = section.footer

paragraph = footer.paragraphs[0]

paragraph.text = "居左頁腳\t居中頁腳\t居右頁腳"

paragraph.style = document.styles["Footer"] # 可省略

document.save('實例.docx') # 保存文件

效果:

4、刪除頁眉/頁腳

可以通過將 True 分配給其 .is_linked_to_previous 屬性來刪除不需要的頁眉/頁腳 :

header.is_linked_to_previous = True

footer.is_linked_to_previous = True

5、添加頁眉/頁腳定義

通過將 False 分配給其 .is_linked_to_previous 屬性,可以為缺少的部分提供顯式頁眉/頁腳定義:

print(header.is_linked_to_previous) # >>> True

header.is_linked_to_previous = False

print(header.is_linked_to_previous)# >>> False

print(footer.is_linked_to_previous) # >>> True

footer.is_linked_to_previous = False

print(footer.is_linked_to_previous)# >>> False

新添加的頁眉/頁腳定義包含一個空段落。

注意:

在已經(jīng)具有頁眉定義的頁眉上將 False 分配給 .is_linked_to_previous 不會執(zhí)行任何操作。

如果第2節(jié)的頁眉繼承自第1節(jié),那編輯第2節(jié)的頁眉時,實際上是改變了第1節(jié)頁眉的內(nèi)容。除非你首先明確地為第2節(jié)的.is_linked_to_previous屬性賦值為False,否則不會為第2節(jié)添加一個新的頁眉定義。

六、樣式

Word 中的樣式是一組可以一次性應用于文檔元素的規(guī)范。 Word 具有段落樣式、字符樣式、表格樣式和編號定義。它們分別應用于段落、文本、表格和列表。

1、標識屬性

樣式具有三個標識屬性,名稱name、style_id 和類型 type。

1)     每個樣式的名稱屬性是固定的、唯一的標識符,用于訪問目的。

2)     樣式的 style_id 在內(nèi)部用于將內(nèi)容對象(例如段落)設置為其樣式的鍵。然而,這個值是由 Word 自動生成的,不能保證在保存過程中保持穩(wěn)定。通常,樣式 id 只需從本地化樣式名稱中刪除空格即可形成,但也有例外。 python-docx 的用戶通常應該避免使用樣式 id,除非他們對所涉及的內(nèi)部結(jié)構有信心。

3)     樣式的類型是在創(chuàng)建時設置的,不能更改。

2、樣式類型

1)內(nèi)置樣式 built-in style

Word中內(nèi)置的276種預設樣式之一,如 "Heading 1"。

樣式定義存儲在 .docx 包的 styles.xml 部分中,但內(nèi)置樣式定義存儲在 Word 應用程序本身中,并且在實際使用之前不會寫入 styles.xml。

一個內(nèi)置的樣式可以是定義的或潛在的。一個尚未定義的內(nèi)置樣式被稱為潛在樣式。

定義的和潛在的內(nèi)置樣式都可以作為選項出現(xiàn)在Word的樣式面板和樣式庫中。

2)自定義樣式 custom style

也稱為用戶定義樣式,在 Word 文檔中定義的任何非內(nèi)置樣式的樣式。請注意,自定義樣式不能是潛在樣式。

3)潛在樣式 latent style

文檔中沒有定義的內(nèi)置樣式在該文檔中稱為潛在樣式。

根據(jù)文檔的 LatentStyles 對象中的設置,潛在樣式可以作為選項出現(xiàn)在 Word 用戶界面中。

潛在樣式定義基本上是一個存根樣式定義,除了樣式名稱外,它最多具有五個行為屬性,通過為每個行為屬性定義默認值可以節(jié)省額外的空間。

因此,只有那些與默認值不同的樣式需要被定義,而符合所有默認值的樣式則不需要潛伏樣式定義。

4)推薦樣式列表 recommended style list

當從 "列表:"下拉框中選擇 "推薦 "時,出現(xiàn)在樣式工具箱或面板中的一個樣式列表。

5)樣式庫 Style Gallery

出現(xiàn)在Word用戶界面功能區(qū)的示例樣式的選擇,可以通過點擊其中的一個來應用。

6)行為屬性

樣式的屬性分為兩類,行為屬性和格式屬性。其中行為屬性控制樣式出現(xiàn)在Word用戶界面中的時間和位置。

樣式有五個行為屬性:

隱藏 hidden

使用時不隱藏 unhide_when_used

優(yōu)先級 priority

快速樣式 quick_style

鎖定 locked

除priority 屬性采用整數(shù)值外,其他四個樣式行為屬性是三態(tài)的,可以取值 True(打開)、False(關閉)或 None(繼承)。

這五個行為屬性會影響樣式列表和樣式庫中樣式。

如果一個樣式的 hidden 屬性為 False(默認值),它就會出現(xiàn)在推薦列表中。

如果樣式未隱藏且其 quick_style 屬性為 True,則它也會出現(xiàn)在樣式庫中。

如果隱藏樣式的 unhide_when_used 屬性為 True,則其隱藏屬性在第一次使用時設置為 False。

樣式列表和樣式庫中的樣式按優(yōu)先級 priority 排序,然后按字母順序排列相同優(yōu)先級的樣式。

如果樣式的鎖定locked屬性為 True 并且為文檔打開了格式限制,則該樣式將不會出現(xiàn)在任何列表或樣式庫中,并且不能應用于內(nèi)容。

比如以下代碼將導致“Body Text”段落樣式首先出現(xiàn)在樣式庫中:

from docx import Document

document = Document()

style = document.styles['Body Text']

style.hidden = False

style.quick_style = True

style.priorty = 1

而此代碼將從樣式庫中刪除“Normal”段落樣式,但允許它保留在推薦列表中:

style = document.styles['Normal']

style.hidden = False

style.quick_style = False

3、訪問樣式

使用 Document.styles 屬性可以訪問樣式:

document = Document()

styles = document.styles

print(styles)

#>>  

Styles 對象可以按以名稱定義的樣式的字典式訪問:

print(styles['Normal'])

#>>  _ParagraphStyle('Normal') id: 2612711224152

Styles 對象也是可迭代的。通過使用 BaseStyle 上的標識屬性,可以生成已定義樣式的各種子集。

例如,此代碼將生成已定義段落樣式的列表:

from docx import Document

from docx.enum.style import WD_STYLE_TYPE

document = Document()

styles = document.styles

paragraph_styles = [s for s in styles if s.type == WD_STYLE_TYPE.PARAGRAPH]

for style in paragraph_styles:

print(style.name)

4、應用樣式

Paragraph、Run 和 Table 對象各有一個樣式屬性,將樣式對象分配給此屬性會應用該樣式:

from docx import Document

document = Document()

paragraph = document.add_paragraph()

print(paragraph.style)  # _ParagraphStyle('Normal') id: 2493830027136

print(paragraph.style.name) #'Normal'

paragraph.style = document.styles['Heading 1']

print(paragraph.style.name) # 'Heading 1'

也可以直接指定樣式名稱:

paragraph.style = 'List Bullet'

print(paragraph.style)  

#  _ParagraphStyle('List Bullet') id: 1843658186312

print(paragraph.style.name)  

#  'List Bullet'

樣式也可以在創(chuàng)建時使用樣式對象或其名稱進行設置:

paragraph = document.add_paragraph(style='Body Text')

print(paragraph.style.name) # 'Body Text'

body_text_style = document.styles['Body Text']

paragraph = document.add_paragraph(style=body_text_style)

print(paragraph.style.name) #'Body Text'

5、添加或刪除樣式

可以通過指定名稱和樣式類型將新樣式添加到文檔中:

from docx import Document

from docx.enum.style import WD_STYLE_TYPE

document = Document()

styles = document.styles

style = styles.add_style('Citation', WD_STYLE_TYPE.PARAGRAPH)

print(style.name)   # 'Citation'

print(style.type)   # PARAGRAPH (1)

使用 base_style 屬性來指定新樣式應該繼承格式設置的樣式:

from docx import Document

from docx.enum.style import WD_STYLE_TYPE

document = Document()

styles = document.styles

style = styles.add_style('Citation', WD_STYLE_TYPE.PARAGRAPH)

print(style.base_style) # None

style.base_style = styles['Normal']

print(style.base_style) # _ParagraphStyle('Normal') id: 1539328207336

print(style.base_style.name)    # 'Normal'

調(diào)用delete() 方法可從文檔中刪除樣式:

from docx import Document

document = Document()

styles = document.styles

print(len(styles))  # 164

styles['Normal'].delete()

print(len(styles))  # 163

注意:通過Style.delete() 方法從文檔中刪除樣式的定義,不會影響應用該樣式的文檔中的內(nèi)容。

文檔中未定義樣式的內(nèi)容使用該內(nèi)容對象的默認樣式,例如在段落的情況下為“Normal”。

6、定義段落格式

段落樣式和表格樣式都允許指定段落格式。這些樣式通過其 paragraph_format 屬性提供對 ParagraphFormat 對象的訪問。

下面是一個示例,說明如何創(chuàng)建具有 1/4 英寸懸掛縮進、上方 12 磅間距和孤行控制的段落樣式:

from docx.enum.style import WD_STYLE_TYPE

from docx.shared import Inches, Pt

document = Document()

style = document.styles.add_style('Indent', WD_STYLE_TYPE.PARAGRAPH)

paragraph_format = style.paragraph_format

paragraph_format.left_indent = Inches(0.25)

paragraph_format.first_line_indent = Inches(-0.25)

paragraph_format.space_before = Pt(12)

paragraph_format.widow_control = True

7、使用特定段落的樣式屬性

段落樣式具有 next_paragraph_style 屬性,該屬性指定在該樣式的段落之后插入的新段落的樣式。

一般當樣式在一個序列中只出現(xiàn)一次時最有用,例如標題。在這種情況下,段落樣式可以在完成標題后自動設置回正文樣式。

對于正文段落,后續(xù)段落應采用與當前段落相同的樣式。如果未指定下一個段落樣式,則默認通過應用相同的樣式。

下面是如何將Heading 1樣式的下一段樣式更改為正文文本的示例:

from docx import Document

document = Document()

styles = document.styles

styles['Heading 1'].next_paragraph_style = styles['Body Text']

可以通過設置None 或樣式本身來恢復默認行為:

from docx import Document

document = Document()

styles = document.styles

styles['Heading 1'].next_paragraph_style = styles['Body Text']

heading_1_style = styles['Heading 1']

print(heading_1_style.next_paragraph_style.name)    #>>>  'Body Text'

heading_1_style.next_paragraph_style = heading_1_style

print(heading_1_style.next_paragraph_style.name)    #>>>  'Heading 1'

heading_1_style.next_paragraph_style = None

print(heading_1_style.next_paragraph_style.name)    #>>>  'Heading 1'

8、使用潛在樣式

1)訪問文檔中的潛在樣式

文檔中的潛在樣式可從樣式對象訪問:

document = Document()

latent_styles = document.styles.latent_styles

LatentStyles對象支持len()、迭代和按樣式名稱的字典式訪問:

from docx import Document

document = Document()

latent_styles = document.styles.latent_styles

print(len(latent_styles))   # 137

latent_quote = latent_styles['Quote']

print(latent_quote)  #

print(latent_quote.priority)   # 29

latent_style_names = [ls.name for ls in latent_styles]

print(latent_style_names)

2)更改潛在樣式默認值

LatentStyles 對象還提供對當前文檔中內(nèi)置樣式的默認行為屬性的訪問。

這些默認值為_LatentStyle定義的沒有定義的屬性以及沒有明確的潛在樣式定義的內(nèi)置樣式的所有行為屬性提供值。

print(latent_styles.default_to_locked) #>>>False

latent_styles.default_to_locked = True

print(latent_styles.default_to_locked) #>>> True

3)添加潛在樣式定義

可以使用 LatentStyles 上的 add_latent_style() 方法添加新的潛在樣式。

此代碼為內(nèi)置樣式“List Bullet”添加了一個新的潛在樣式,將其設置為出現(xiàn)在樣式庫中:

from docx import Document

document = Document()

latent_styles = document.styles.latent_styles

latent_style = latent_styles.add_latent_style('List Bullet')

latent_style.hidden = False

latent_style.priority = 2

latent_style.quick_style = True

4)刪除潛在樣式定義

可以通過調(diào)用其 delete() 方法來刪除潛在樣式定義:

latent_styles['Light Grid'].delete()

    本站是提供個人知識管理的網(wǎng)絡存儲空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點。請注意甄別內(nèi)容中的聯(lián)系方式、誘導購買等信息,謹防詐騙。如發(fā)現(xiàn)有害或侵權內(nèi)容,請點擊一鍵舉報。
    轉(zhuǎn)藏 分享 獻花(0

    0條評論

    發(fā)表

    請遵守用戶 評論公約