本文實例分析了Python docx庫用法。分享給大家供大家參考,具體如下:
打開及保存文件:
from docx import Documentdocument = Document('test.docx')document.save('test.docx')添加文本:
document.add_paragraph('test text')調整文本位置格式為居中:
from docx import Documentfrom docx.enum.text import WD_ALIGN_PARAGRAPHdocument = Document('test.docx')paragraph = document.add_paragraph('123')paragraph.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTERdocument.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_formatparagraph_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 = TrueWD_UNDERLINE 中有所有下劃線格式
調用樣例:
run.underline = WD_UNDERLINE.DOT_DASH
字體顏色:
from docx.shared import RGBColortest = document.add_paragraph().add_run('color')font = test.fontfont.color.rgb = RGBColor(0x42, 0x24 , 0xE9)調用預設顏色:
from docx.enum.dml import MSO_THEME_COLORfont.color.theme_color = MSO_THEME_COLOR.ACCENT_1
更多關于Python相關內容感興趣的讀者可查看本站專題:《Python數據結構與算法教程》、《Python函數使用技巧總結》、《Python字符串操作技巧匯總》、《Python入門與進階經典教程》及《Python文件與目錄操作技巧匯總》
希望本文所述對大家Python程序設計有所幫助。
新聞熱點
疑難解答