跳到主要內容

[python] 使用 python 控制 docx 範例

因為同事的需求,無職 a 我就又再度幫忙同事寫一些小程式。

這些小程式雖然簡單,但是聽到如果不幫忙寫程式解決,以手工作業的"大量人天" 的後果真的是讓人吐血。

他們有一份工作,需要產出一份很多很多很多資料圖片的判釋報告,要把數百張圖片剪裁成特定大小,加上圖說之後放入 word 裡面。

聽到的做法是...一張一張插圖!! wooow! That's really shocking me! 所以為了前公司同事的幸福,我還是加減寫一下好了。





以下是使用 python 控制 docx 的範例 code:

#-*-coding: utf-8-*-



from docx import Document  # 使用 docx 模組

document = Document() #創建空的 word template

section = document.sections[0]



from docx.shared import Cm, Pt  #加入可調整的 word 單位

from docx.enum.text import WD_ALIGN_PARAGRAPH #處理字串的置中



#調整文件左右上下邊界至 1.27 cm

section.left_margin=Cm(1.27)

section.right_margin=Cm(1.27)

section.top_margin=Cm(1.27)

section.bottom_margin=Cm(1.27)



#把A4文件轉成橫置方向

from docx.enum.section import WD_ORIENT #處理文件的直向/橫向

section.orientation = WD_ORIENT.LANDSCAPE

new_width, new_height = Cm(29.7), Cm(21)

section.page_width = new_width

section.page_height= new_height





#把A4文件單欄內容轉換成雙欄內容

from docx.oxml import OxmlElement

from docx.oxml.ns import qn



sectPr = section._sectPr

cols = sectPr.xpath('./w:cols')[0]

cols.set(qn('w:num'),'2')





#放入一張圖片並指定圖片大小

document.add_picture('test.jpg', width=Cm(13.12), height=Cm(6.98))



#加入章節並調整為置中

paragraph = document.add_paragraph()

paragraph.paragraph_format.alignment=WD_ALIGN_PARAGRAPH.CENTER



#加入字串並調整英文為 New Times, 中文為標楷體

run = paragraph.add_run(u'))

font = run.font

font.name= 'New Times Roman'   #設定英文字體

font.size=Pt(12)

r = run._element

r.rPr.rFonts.set(qn('w:eastAsia'), u'標楷體')  #設定中文字體


#檔案存檔
document.save('demo.docx')

另外要注意的是,當要打包成單獨檔案使用時, pyinstaller 會自動 '忘記' 打包 default template,
遇到這種狀況,我個人是先讓 pyinstaller 自動出 .spec 檔案
然後最後在 .spec 檔案裡面的 datas = [] 改成
datas=[(path.join(site_packages,"docx","templates"), "docx/templates")], 
然後用該 .spec 自動打包,就可以順利完成了!
$> pyinstaller --onefile xxx.spec

留言