python docx库使用样例_Python docx库用法示例分析
本文實例分析了Python docx庫用法。分享給大家供大家參考,具體如下:
打開及保存文件:
from docx import Document
document = Document('test.docx')
document.save('test.docx')
添加文本:
document.add_paragraph('test text')
調整文本位置格式為居中:
from docx import Document
from docx.enum.text import WD_ALIGN_PARAGRAPH
document = Document('test.docx')
paragraph = document.add_paragraph('123')
paragraph.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER
document.save('test.docx')
調整左縮進0.3英寸:
document = Document('test.docx')
paragraph = document.add_paragraph('this is test for left_indent with inches')
paragraph_format = paragraph.paragraph_format
paragraph_format.left_indent = Inches(0.3)
document.save('test.docx')
首行縮進:
paragraph_format.first_line_indent = Inches(0.3)
上行間距:
paragraph_format.space_before = Pt(18)
下行間距:
paragraph_format.space_after = Pt(12)
行距:
paragraph_format.line_spacing = Pt(18)
分頁格式:
緊跟上段:
paragraph_format.keep_together
若本頁無法完全顯示,另起一頁:
paragraph_format.keep_with_next
強制另起一頁:
paragraph_format.page_break_before
字體格式:
p = document.add_paragraph()
run = p.add_run('test typeface')
#加粗
run.font.bold = True
#斜體
run.font.italic = True
#下劃線
run.font.underline = True
WD_UNDERLINE 中有所有下劃線格式
調用樣例:
run.underline = WD_UNDERLINE.DOT_DASH
字體顏色:
from docx.shared import RGBColor
test = document.add_paragraph().add_run('color')
font = test.font
font.color.rgb = RGBColor(0x42, 0x24 , 0xE9)
調用預設顏色:
from docx.enum.dml import MSO_THEME_COLOR
font.color.theme_color = MSO_THEME_COLOR.ACCENT_1
更多關于Python相關內容感興趣的讀者可查看本站專題:《Python數據結構與算法教程》、《Python函數使用技巧總結》、《Python字符串操作技巧匯總》、《Python入門與進階經典教程》及《Python文件與目錄操作技巧匯總》
希望本文所述對大家Python程序設計有所幫助。
時間: 2019-02-14
總結
以上是生活随笔為你收集整理的python docx库使用样例_Python docx库用法示例分析的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 为什么可转债申购后是废单?
- 下一篇: python合并word单元格_pyth