使用python-docx生成Word文檔


轉載:https://www.cnblogs.com/lvye001/p/9821014.html

 

首先是安裝python-docx:(centos環境)

pip  install python-docx

 

基本方法使用:

from  docx import  Document
from  docx.shared import  Pt
from  docx.oxml.ns import  qn
from docx.shared import Inches
 #打開文檔
document = Document()
 #加入不同等級的標題
document.add_heading('Document Title',0)
document.add_heading(u'二級標題',1)
document.add_heading(u'二級標題',2)
 #添加文本
paragraph = document.add_paragraph(u'添加了文本')
 #設置字號
run = paragraph.add_run(u'設置字號')
run.font.size=Pt(24)
 #設置字體
run = paragraph.add_run('Set Font,')
run.font.name='Consolas'
#設置中文字體
run = paragraph.add_run(u'設置中文字體,')
run.font.name=u'宋體'
r = run._element
r.rPr.rFonts.set(qn('w:eastAsia'), u'宋體')
 #設置斜體
run = paragraph.add_run(u'斜體、')
run.italic = True
 #設置粗體
run = paragraph.add_run(u'粗體').bold = True
 #增加引用
document.add_paragraph('Intense quote', style='Intense Quote')
 #增加有序列表
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'
)
 #增加圖片(此處使用相對位置)
document.add_picture('jdb.jpg',width=Inches(1.25))
 #增加表格
復制代碼
table = document.add_table(rows=3,cols=3)
hdr_cells=table.rows[0].cells
hdr_cells[0].text="第一列"
hdr_cells[1].text="第二列"
hdr_cells[2].text="第三列"

hdr_cells = table.rows[1].cells
hdr_cells[0].text = '2'
hdr_cells[1].text = 'aerszvfdgx'
hdr_cells[2].text = 'abdzfgxfdf'

hdr_cells = table.rows[2].cells
hdr_cells[0].text = '3'
hdr_cells[1].text = 'cafdwvaef'
hdr_cells[2].text = 'aabs zfgf'
復制代碼
 #增加分頁
document.add_page_break()
#保存文件
document.save('demo.docx')

 

效果展示:

 
 
 
 
 
下面是一小段代碼,實現循環寫入當前目錄里的圖片


免責聲明!

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



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