Python-docx


python-docx包可以用來創建docx文檔,並對現有文檔進行更改,包含段落、分頁符、表格、圖片、標題、樣式等幾乎所有的word文檔中能常用的功能都包含了

只能解析docx文件,解析不了doc文件

官方文檔:

https://python-docx.readthedocs.io/en/latest/user/text.html

https://python-docx.readthedocs.io/en/latest/index.html

from docx import Document #初始化對象
from docx.shared import Inches  #定義英尺
from docx.shared import Pt  #定義像素大小
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.oxml.ns import qn #定義style的
from docx.shared import RGBColor

#打開docx文件
document = Document()

#增加一段
paragraph = document.add_paragraph('This is a demo.')

#在段落前直接插入一個新段落
prior_paragraph = paragraph.insert_paragraph_before('welcome!')

#這一類屬性,每個有三種狀態
#True 為使用屬性;False 為不使用屬性;None 默認屬性繼承自上一個字體
paragraph = document.add_paragraph()
paragraph.add_run('Lorem ipsum')
run = paragraph.add_run(' dolor')
run.bold = True
run.font.name=u'宋體'
r = run._element
r.rPr.rFonts.set(qn('w:eastAsia'), u'宋體')
paragraph.add_run(' hello').underline = True 
paragraph.add_run(u'斜體、').italic = True 
paragraph.add_run(u'設置中文字體,') 
paragraph.add_run(u'設置字號').font.size=Pt(24) 

#添加文本
p = document.add_paragraph('test')

#文本居中
#WD_ALIGN_PARAGRAPH 存儲了多種對齊格式
#例如:WD_ALIGN_PARAGRAPH.LEFT,左對齊;WD_ALIGN_PARAGRAPH.RIGHT,右對齊
p.alignment = WD_ALIGN_PARAGRAPH.CENTER 

#左縮進
p.left_indent = Inches(0.3)

#首行縮進
p.first_line_indent = Inches(0.3)

#上行間距
p.space_before = Pt(18)

#下行間距
p.space_after = Pt(12)

#添加標題
document.add_heading('The REAL meaning of the universe')
document.add_heading('The role of dolphins', level = 2)

#添加引用
document.add_paragraph('Intese quote',style="Intense Quote")

#添加分頁符
document.add_page_break()

#添加表
table = document.add_table(rows=2,cols=2)
cell = table.cell(0,0)
cell.text = 'cell_00'
table.cell(0,1).text = 'cell_01'
row = table.rows[1]
row.cells[0].text = 'cell_10'
row.cells[1].text = 'cell_11'

#行列計數
row_count = len(table.rows)
col_count = len(table.columns)

#添加圖片
document.add_picture('1.png',width=Inches(1.25))

#應用字符樣式
paragraph = document.add_paragraph('Normal text, ')
paragraph.add_run('text with emphasis','Emphasis')

#增加有序列表
document.add_paragraph(
    u'有序列表元素1',style='List Number'
)
document.add_paragraph(
    u'有序列表元素2',style='List Number'
)

#增加無序列表
document.add_paragraph(
    u'無序列表元素1',style='List Bullet'
)
document.add_paragraph(
    u'無序列表元素2',style='List Bullet'
)
#或者paragraph = document.add_paragraph('Lorem ipsum dolor sit amet.')
#   paragraph.style = 'ListBullet'

document.save('test.docx')

結果截圖如下:

 


免責聲明!

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



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