用 python 來操作word文件(使用 docx 庫)


實例一:

from docx import Document
from docx.enum.text import WD_ALIGN_PARAGRAPH from docx.oxml.ns import qn # 中文格式 from docx.shared import Pt # 磅數 from docx.shared import Inches # 圖片尺寸 import time today = time.strftime("%Y{y}%m{m}%d{d}", time.localtime()).format(y="年", m="月", d="日") price = input("請輸入今日價格:") company_list = ["客戶1", "客戶2", "客戶3", "客戶4", "客戶5", "客戶6", "客戶7", "客戶8", "客戶9", "客戶10"] for i in company_list: document = Document() document.styles["Normal"].font.name = u"微軟雅黑" document.styles["Normal"].font.size = Pt(14) # 設置文檔的基礎字體 document.styles['Normal']._element.rPr.rFonts.set(qn('w:eastAsia'), u'微軟雅黑') # 設置文檔的基礎樣式  document.add_picture("d:/無標題.png", width=Inches(6)) # 在文件最上頭插入圖片作為文件紅頭,寬度為6英寸  p1 = document.add_paragraph() # 初始化建立第一個自然段 p1.alignment = WD_ALIGN_PARAGRAPH.CENTER # 對齊方式為居中,沒有這句默認左對齊 run1 = p1.add_run("關於下達%s產品價格的通知" % (today)) # 這里是第一段的內容 run1.font.name = "微軟雅黑" # 設置西文字體 run1._element.rPr.rFonts.set(qn('w:eastAsia'), u'微軟雅黑') # 設置中文字體 run1.font.size = Pt(21) # 設置字體大小為21磅 run1.font.bold = True # 設置加粗 p1.space_after = Pt(5) # 設置段后距離5磅 p1.space_before = Pt(5) # 設置段后距離5磅  p2 = document.add_paragraph() run2 = p2.add_run(i + ": ") # 這里是對客戶的稱呼 run2.font.name = "仿宋_GB2312" run2._element.rPr.rFonts.set(qn('w:eastAsia'), u'仿宋_GB2312') run2.font.size = Pt(16) run2.font.bold = True p3 = document.add_paragraph() run3 = p3.add_run(" 根據公司安排,為提供優質客戶服務,我單位現將價格通知如下。 ") run3.font.name = "仿宋_GB2312" run3._element.rPr.rFonts.set(qn('w:eastAsia'), u'仿宋_GB2312') run3.font.size = Pt(16) run3.font.bold = True table = document.add_table(rows=3, cols=3, style="Table Grid") table.cell(0, 0).merge(table.cell(0,2)) table_run1 = table.cell(0,0).paragraphs[0].add_run("XXX產品報價表") table_run1.font.name = u"隸書" table_run1.font.bold = True table_run1._element.rPr.rFonts.set(qn('w:eastAsia'), u'隸書') table.cell(0, 0).paragraphs[0].alignment = WD_ALIGN_PARAGRAPH.CENTER table.cell(1, 0).text = "日期" table.cell(1, 1).text = "價格" table.cell(1, 2).text = "備注" table.cell(2, 0).text = today table.cell(2, 1).text = str(price) table.cell(2, 2).text = "" p4 = document.add_paragraph() p4.alignment = WD_ALIGN_PARAGRAPH.CENTER run4 = p4.add_run(" (聯系人: 小楊 電話:18888888888) ") run4.font.name = "仿宋_GB2312" run4._element.rPr.rFonts.set(qn('w:eastAsia'), u'仿宋_GB2312') run4.font.size = Pt(16) run4.font.bold = True document.add_page_break() p5 = document.add_paragraph() run4 = p5.add_run("此處是廣告") document.save("%s-價格通知.docx" % i)

   效果圖:

 

 

 

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

  基本用法:

 #!/usr/bin/env python
 #coding: utf-8
  
 from docx import Document
 from docx.shared import Inches
  
 #創建 Document 對象,相當於打開一個 word 文檔
 document = Document()
  
 #向文檔中添加一個標題,標題級別設置為0級
 document.add_heading('This is title', level=0)
 
 #向文檔中添加一個段落,並將段落引用賦給變量 p
 #使用 add_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
 
 #添加標題和段落,采用不同的形式
 document.add_heading('This is Heading, level 1', level=1)
 document.add_paragraph('Intese quote',style="Intense Quote")
 document.add_paragraph('first item in unordered list', style='List Bullet')
 document.add_paragraph('first item in ordered list', style='List Number')
 
 #添加圖片,設置圖片大小
 document.add_picture(r"D:\picture\a.jpg", width=Inches(2.25))
 
 #添加表格,填入表格內容
 table = document.add_table(rows=2, cols=2)
 table.cell(0,0).text = "cell_00"
 table.cell(0,1).text = "cell_01"
 table.cell(1,0).text = "cell_10"
 table.cell(1,1).text = "cell_11"
 
 #保存文本
 document.save('demo.docx')

   效果展示:

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

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

 

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

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

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

  塊等級(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,右對齊

 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)

 內聯等級,及其屬性  

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

    內聯對象的屬性指定了字體,例如粗體(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

 color

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

#使用內建主題設置顏色
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