當(dāng)然要用第三方庫啦 :)
使用以下命令安裝:
pip install python-docx
使用該庫的基本步驟為:
1.建立一個(gè)文檔對(duì)象(可自動(dòng)使用默認(rèn)模板建立,也可以使用已有文件)。
2.設(shè)置文檔的格式(默認(rèn)字體、頁面邊距等)。
3.在文檔對(duì)象中加入段落文本、表格、圖像等,并指定其樣式。
4.保存文檔。
注:本庫僅支持生成Word2007以后版本的文檔類型,即擴(kuò)展名為.docx 的。
下面分步介紹其基本使用方法:
步驟一:
from docx import Document
doc = Document() #以默認(rèn)模板建立文檔對(duì)象
doc = Document('a.docx') # 讀取a.docx文檔,建立文檔對(duì)象
步驟二:
from docx.shared import Inches,Pt
def chg_font(obj,fontname='微軟雅黑',size=None):
## 設(shè)置字體函數(shù)
obj.font.name = fontname
obj._element.rPr.rFonts.set(qn('w:eastAsia'),fontname)
if size and isinstance(size,Pt):
obj.font.size = size
distance = Inches(0.3)
sec = doc.sections[0] # sections對(duì)應(yīng)文檔中的“節(jié)”
sec.left_margin = distance # 以下依次設(shè)置左、右、上、下頁面邊距
sec.right_margin = distance
sec.top_margin = distance
sec.bottom_margin = distance
sec.page_width =Inches(12) #設(shè)置頁面寬度
sec.page_height = Inches(20) #設(shè)置頁面高度
##設(shè)置默認(rèn)字體
chg_font(doc.styles['Normal'],fontname='宋體')
步驟三:
1.添加段落文本
paragraph =doc.add_paragraph('text....')
ph_format =paragraph.paragraph_format
ph_format.space_before =Pt(10) #設(shè)置段前間距
ph_format.space_after =Pt(12) #設(shè)置段后間距
ph_format.line_spacing=Pt(19) #設(shè)置行間距
如果希望同一段落中的文本格式不同,就需要使用Run對(duì)象(可以理解為可以單獨(dú)設(shè)置格式的段落內(nèi)對(duì)象)。
如:
run = paragraph.add_run('text...')
run.bold = True #設(shè)置字體為粗體
chg_font(run,fontname='微軟雅黑', size=Pt(12)) #設(shè)置字體和字號(hào)
2.添加表格,并寫入相關(guān)內(nèi)容
tab =doc.add_table(rows=4,cols=4) #添加一個(gè)4行4列的空表
cell=tab.cell(1,3) #獲取某單元格對(duì)象(從0開始索引)
在單元格中添加文本:
cell.text='abc'
在單元格中添加多行文本(指定轉(zhuǎn)行)
ph =cell.paragraphs[0]
run=ph.add_run(‘text....’)'
run.add_break() # 添加一個(gè)折行
run.add_picture('a.png') # 插入圖像,可以是內(nèi)存中的圖像,width=Inches(1.0)指定寬度。
3.在文檔中添加圖像:
doc.add_picture('a.png')
步驟四:
doc.save('a.docx') # 保存圖像
做一個(gè)簡單的測試,其生成文檔的速度還是比較快的。感覺比以前用reportlab庫生成PDF文檔要快不少呢!
下圖是用此方式生成docx文檔的截圖:
聯(lián)系客服