用python操作docx


docx 庫

文章結構:

  一、docx 基本用,創建 docx 文件並添加數據

  二、深入理解文本格式(format),並設置所格式屬性(attribute)

  三、深入理解樣式(styles),以及如何運用樣式

  四、常用樣式(style)示例

 

一、docx基本用法,創建docx 文件並添加數據

  官方文檔:https://python-docx.readthedocs.org/en/latest/

  docx 可以操作 doxc 格式文件

  linux 安裝 sudo pip install python_docx (不要安裝錯了,python_docx 是新版本,如果只是安裝 docx 有些 API 會不匹配)

  windows 安裝 pip install python_docx

  基本用法:

復制代碼
 1 #!/usr/bin/env python
 2 #coding: utf-8
 3 
 4 from docx import Document
 5 from docx.shared import Inches
 6 
 7 #創建 Document 對象,相當於打開一個 word 文檔
 8 document = Document()
 9 
10 #向文檔中添加一個標題,標題級別設置為0級
11 document.add_heading('This is title', level=0)
12 
13 #向文檔中添加一個段落,並將段落引用賦給變量 p
14 #使用 add_run 方法追加字段,並設置格式
15 p = document.add_paragraph('This is paragraph')
16 p.add_run('bold').bold = True
17 p.add_run(' and some ')
18 p.add_run('italic.').italic = True
19 
20 #添加標題和段落,采用不同的形式
21 document.add_heading('This is Heading, level 1', level=1)
22 document.add_paragraph('Intese quote',style="Intense Quote")
23 document.add_paragraph('first item in unordered list', style='List Bullet')
24 document.add_paragraph('first item in ordered list', style='List Number')
25 
26 #添加圖片,設置圖片大小
27 document.add_picture(r"D:\picture\a.jpg", width=Inches(2.25))
28 
29 #添加表格,填入表格內容
30 table = document.add_table(rows=2, cols=2)
31 table.cell(0,0).text = "cell_00"
32 table.cell(0,1).text = "cell_01"
33 table.cell(1,0).text = "cell_10"
34 table.cell(1,1).text = "cell_11"
35 
36 #保存文本
37 document.save('demo.docx')
復制代碼

   效果展示:

<--------------------            start            -------------------->

<--------------------            end            -------------------->

 

二、深入理解文本格式(format),並設置所格式屬性(attribute)

  根據官方文檔所述,word 中主要有兩種用文本格式等級:塊等級(block-level)和內聯等級(inline-level)

  word 中大部分內容都是由這兩種等級的對象組成的

  (其他的諸如眉頁、引腳等,docx 庫的作者還在開發中)

  塊等級(block-level)

    段落是 word 文件中的主要塊對象(block-level object)

    塊等級項(block-level item)主要任務是將文本格式從左邊界向右邊界展示(flows);\

    對於段落而言,邊界就是分段標識,或者是文本的列邊界

    列表(table)也是塊對象(block-level object)

  內聯等級(inline-level): 

    內聯對象(inline-level object)是塊對象(block-level object)的組成部分

    塊對象的所有內容都包含在內聯對象中,一個塊對象由一個或多個內聯對象組成

    run 是常用的內聯對象,例如:

         p = document.add_paragraph('This is paragraph')
         p.add_run('bold').bold = True
         p.add_run(' and some ')
         p.add_run('italic.').italic = True

    這個例子中一個段落(塊對象)包含三個 run(內聯對象),每一個 run 都設置有不同屬性

  塊等級,及其屬性

    塊對象一般包括:段落(paragraph)、圖片(inline picture)、表(table)、標題(heading)、\

    有序列表(numbered lists)、無序列表(bullets lists)

    塊對象的屬性指定了塊對象所在的位置,例如縮進、段間距離

    常用屬性:

      alignment,水平對齊

復制代碼
from docx.enum.text import WD_ALIGN_PARAGRAPH

paragraph = document.add_paragraph("hello")
paragraph_format = paragraph.paragraph_format

#設置段落水平右對齊
paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER

#WD_ALIGN_PARAGRAPH 存儲了多種對齊格式,例如:
#WD_ALIGN_PARAGRAPH.LEFT,左對齊;WD_ALIGN_PARAGRAPH.RIGHT,右對齊
#更多參見https://python-docx.readthedocs.org/en/latest/api/enum/WdAlignParagraph.html#wdparagraphalignment
復制代碼

      indent,縮進

復制代碼
from docx.shared import Inches
from docx.shared import Pt

#設置段落從左開始縮進,使用Inches來衡量 paragraph_format.left_indent = Inches(0.5) #設置段落從右開始縮進,使用Pt來衡量 paragraph_format.right_indent = Pt(20) #設置段落第一行縮進,可以與上兩個縮進疊加 paragraph_format.first_line_indent = Inches(0.5)
復制代碼

      space,行間距

復制代碼
from docx.shared import Pt

#設置與上一段間隔 Pt(5) paragraph.space_after = Pt(5) #設置與下一段間隔 Pt(10) paragraph.space_before = Pt(10)
復制代碼

      其他熟悉如字間距、頁碼等屬性,參見文檔:https://python-docx.readthedocs.org/en/latest/user/text.html

  內聯等級,及其屬性  

    內聯對象一般包括:文字、句子、段落

    內聯對象的屬性指定了字體,例如粗體(bold)、斜體(italic)、大小(size)等等

    常用屬性:

      name and size

復制代碼
document = Document()
paragraph = document.add_paragraph()

run = paragraph.add_run("hellohellohello")
font = run.font

#設置字體樣式
font.name = 'Calibri'
#設置字體大小
font.size = Pt(55)
復制代碼

      bold 、underline and underline

復制代碼
#設置為斜體
font.italic = True
#不設置下划線
font.underline = False
#設置粗體為繼承上一個字體的格式
font.bold = None

#這一類屬性,每個有三種狀態
#True 為使用屬性;False 為不使用屬性;None 默認屬性繼承自上一個字體

#此外,underline 屬性還可以設置值,例如
font.underline = WD_UNDERLINE.DOT_DASH
#更多選項參見http://python-docx.readthedocs.org/en/latest/api/enum/WdUnderline.html#wdunderline
復制代碼

      color

復制代碼
#以RGB方式設置顏色
from docx.shared import RGBColor
font.color.rgb = RGBColor(0x42, 0x24, 0xE9)

#使用內建主題設置顏色
#詳細說明參見https://python-docx.readthedocs.org/en/latest/api/enum/MsoThemeColorIndex.html#msothemecolorindex
from docx.enum.dml import MSO_THEME_COLOR
font.color.theme_color = MSO_THEME_COLOR.ACCENT_1
復制代碼

 

三、深入理解樣式(styles),以及如何運用樣式

  在 word 中,樣式包括:段落樣式(paragraph styles)、字符樣式(character styles)、表樣式(table styles)、列表樣式(numbering styles)

  樣式類似於前端開發的 CSS,一處定義,處處使用

  docx 庫內的 styles 樣式不包含 word 中全部的樣式,有一些還在開發中,但是基本夠用

  Document 的屬性 styles,包含了所有 docx 提供的可用樣式  

  選取段落可用樣式

復制代碼
#顯示所有段落樣式
from docx.enum.style import WD_STYLE_TYPE
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)

#styles 為 Document 的屬性,style 為段落的屬性
#除了段落(paragraph),還有 run,表(table)有 style 屬性
復制代碼

  段落設置樣式

復制代碼
document = Document()

#從styles中選取樣式
paragraph = document.add_paragraph()
paragraph.style = document.styles['Heading 1']

#用樣式名稱直接賦值
paragraph2 = document.add_paragraph()
paragraph2.style = 'List Bullet'

#在創建段落時賦值
paragraph = document.add_paragraph(style='Body Text')
復制代碼

   定義樣式(style)中的字符格式(character format)

    定義樣式中的字符格式后,所有運用此樣式的段落都有相應的字符格式

復制代碼
document = Document()

#從樣式庫中選取 'Normal' 樣式,並提取 'Normal' 樣式的字符屬性
style = document.styles['Normal']
font = style.font

#設置樣式中的字符屬性 ,操作方法和上面改變內聯對象屬性方法一致
font.name = "Microsoft YaHei UI"
font.size = Pt(50)

#將設置好字符屬性的樣式運用到段落中
p = document.add_paragraph("change font attribution", style = 'Normal')
復制代碼

   定義樣式(style)中的段落格式(paragraph format)

    定義樣式中的段落格式后,所有運用此樣式的段落都有相應的段落格式

復制代碼
document = Document()
styles = document.styles

#選取 style,並設置 style 中的段落格式
style = styles['Heading 2']
para_format = style.paragraph_format
para_format.left_indent = Pt(20)
para_format.widow_control = True

#將設置好段落格式的 style 運用到段落中
p = document.add_paragraph('This is Heading, level 1', style = style)
復制代碼

   簡單總結

    文章第二部分直接設置段落的格式(paragraph.format),字符的格式(run.font)

    在這一部分,運用了 style 對象,統一設置了段落格式、字符格式

    一旦 style 對象設置好了以后,可以多次反復利用

    style 對象是從文件對象中提取(document.styles)的,docx 提供的 Style 類對象

 

四、常用樣式(style)示例

  段落樣式

復制代碼
from docx.enum.style import WD_STYLE_TYPE
from docx import *

document = Document()
styles = document.styles

#生成所有段落樣式
for s in styles:
    if s.type == WD_STYLE_TYPE.PARAGRAPH:
        document.add_paragraph('Paragraph style is : '+ s.name, style = s)

document.save('para_style.docx')
復制代碼

  字符樣式

復制代碼
from docx.enum.style import WD_STYLE_TYPE
from docx import *

document = Document()
styles = document.styles
para = document.add_paragraph()

#生成所有字符樣式
for s in styles:
    if s.type == WD_STYLE_TYPE.CHARACTER:
        run = para.add_run("Character style is:  "+s.name+"\n")
        run.style = s

document.save('character_style.docx')
復制代碼

  表格樣式

復制代碼
from docx.enum.style import WD_STYLE_TYPE
from docx import *

document = Document()
styles = document.styles

#生成所有表樣式
for s in styles:
    if s.type == WD_STYLE_TYPE.TABLE:
        document.add_paragraph("Table style is :  "+ s.name)
        document.add_table(3,3, style = s)
        document.add_paragraph("\n")

document.save('demo2.docx')
復制代碼


免責聲明!

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



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