無(wú)論在工作,還是在生活當(dāng)中,主要用到計(jì)算機(jī),無(wú)可避免的就要與office打交道,而其中Word、Excel、PPT是用得最多的。
這次咱就用Python3來(lái)操作一下Word文檔。
1
想要Python獲得操作docx文檔的能力,得先安裝docx開發(fā)包。別的不多說(shuō),趕緊打開命令行窗口,輸入:pip install python-docx。稍等片刻就安裝好了。
悄悄告訴你一個(gè)好消息,docx是跨平臺(tái)的。可以支持Windows、macOS、Ubuntu等操作系統(tǒng)。

2
開啟自己喜歡的操作系統(tǒng),如Windows,打開自己喜歡的開發(fā)工具,如PyCharm。新建工程這些我就不多說(shuō)了,直接上生成Word并插入內(nèi)容的代碼,末尾附上代碼里用到的圖片(good.png),希望你不喜歡。
fromdocx?importDocument
fromdocx.oxml.ns?importqn
fromdocx.shared?importPt
fromdocx.enum.text?importWD_PARAGRAPH_ALIGNMENT
fromdocx.shared?importInches
fromdocx.shared?importRGBColor
#?聲明一個(gè)word對(duì)象
doc = Document()
#?設(shè)置字體樣式
doc.styles['Normal'].font.name = u'宋體'
doc.styles['Normal'].element.rPr.rFonts.set(qn('w:eastAsia'), u'宋體')
# ------添加文檔標(biāo)題-------
paragraph = doc.add_paragraph()
run = paragraph.add_run("?程序員有話說(shuō)")
font = run.font
#?設(shè)置字體大小
font.size = Pt(24)
#?設(shè)置水平居中
paragraph_format = paragraph.paragraph_format
paragraph_format.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
# ------添加一段話-------
content =?"這是一個(gè)最好的時(shí)代,也是一個(gè)最壞的時(shí)代。好的是眾多程序員都加入通過(guò)文字表達(dá)自己想法的步伐,"\
?"不好的是依然圍著技術(shù)轉(zhuǎn),始終不敢釋放自我。你若不信,請(qǐng)聽聽他們的對(duì)話。"
paragraph = doc.add_paragraph(content)
paragraph_format = paragraph.paragraph_format
#?第一行左邊縮進(jìn)
paragraph_format.first_line_indent = Inches(0.3)
# -----添加一個(gè)小標(biāo)題------
paragraph = doc.add_paragraph()
run = paragraph.add_run("同程序員聊天")
paragraph_format = paragraph.paragraph_format
#?段前
paragraph_format.space_after = Pt(15)
#?段后
paragraph_format.space_before = Pt(2)
#?字體加粗和下劃線
font = run.font
font.bold = True
# ----跟銷售人員聊天-----
content =?"大家好,我是西門吹水,做銷售的,現(xiàn)去研發(fā)部找程旭猿聊聊天。你好,程旭猿,在忙什么呢?\n研究Python技術(shù)當(dāng)中。\n"
paragraph = doc.add_paragraph(content)
#?添加下劃線
run = paragraph.add_run("什么是派森來(lái)的?麻煩介紹一下。")
font = run.font
font.underline = True
#?插入表格和內(nèi)容
table = doc.add_table(rows=3, cols=2, style="Medium Grid 1 Accent 1")
table.cell(0,?0).text =?"Python"
table.cell(0,?1).text =?"跨平臺(tái)編程語(yǔ)言"
table.cell(1,?0).text =?"跨平臺(tái)"
table.cell(1,?1).text =?"Windows、macOsS、Ubuntu等"
table.cell(2,?0).text =?"用途"
table.cell(2,?1).text =?"人工智能、Web、桌面系統(tǒng)..."
# -----設(shè)置字體顏色------
doc.add_paragraph("西門吹水:我一句都沒(méi)聽懂,怎么辦法呀?")
paragraph = doc.add_paragraph()
run = paragraph.add_run("程旭猿:給你一張圖片,自己體會(huì)去。")
font = run.font
font.color.rgb = RGBColor(0xFF,?0x00,?0x00)
# -----添加圖片,設(shè)置圖片大小------
doc.add_picture(r"good.png", width=Inches(6.25))
# ------保存word文檔到當(dāng)前目錄下-------
doc.save('demo.docx')
