python docx包_[Python02] Python-docx包的使用,快速处理 Word 文件!
日常需要經(jīng)常處理Word文檔,發(fā)現(xiàn)了一個(gè)新的Python包:Python-docx,處理docx十分方便。
而且這個(gè)包和pandas包結(jié)合使用,可以在word插入excel表格,節(jié)省了很多復(fù)制、粘貼、調(diào)整表格樣式的時(shí)間,真的很方便!
但是要注意:Python-docx只能處理docx、docx、docx文件!
下面給大家介紹一下如何使用Python-docx吧,拋磚引玉~
0. 學(xué)習(xí)思路
一、 基礎(chǔ)!安裝Python-docx,并對(duì)照”官方幫助說明“了解包的對(duì)象和基本函數(shù);這里建議在python交互模式下進(jìn)行,可以直觀的看到返回值和報(bào)錯(cuò)。
二、 出題!自己定義一個(gè)問題并解決,來加深對(duì)包的理解。題目:”創(chuàng)建一個(gè)docx文件,要求輸入2個(gè)表格,并且這個(gè)表格有填充的數(shù)字,表格前有相應(yīng)標(biāo)題。“
三、 進(jìn)階!試試包的更多函數(shù),看會(huì)觸發(fā)什么效果。結(jié)合pandas,學(xué)習(xí)表格和字體、字號(hào)、顏色的處理
一、 基礎(chǔ)
1.1 使用conda安裝python-docx:
conda install -c conda-forge python-docx
沒有了解過conda的同學(xué),可以看看 Anaconda國內(nèi)鏡像停止后,怎么辦?(已恢復(fù)),文中有簡單介紹。
1.2 簡要了解Python-docx:
1 打開/讀取文檔
第一步當(dāng)然是創(chuàng)建文檔并打開啦~
from docx import Document
import os
path = "a.docx"
os.system("touch %s" %path) # 調(diào)用shell命令創(chuàng)建a.docx文件
documentNew = Document() # 不指定路徑是創(chuàng)建文件
documnet = Document(path) # 指定路徑是讀取文件
w(゚Д゚)w 發(fā)現(xiàn)報(bào)錯(cuò) PackageNotFoundError :
docx.opc.exceptions.PackageNotFoundError: Package not found ...
原來是因?yàn)閍.docx中沒有任何內(nèi)容。打開a.docx之后輸入幾個(gè)字符,再重試以上代碼,就不會(huì)報(bào)錯(cuò)了。
2 插入標(biāo)題
使用 add_heading() 或add_paragraph()添加標(biāo)題:
document.add_heading('Document Title', 0)
# 方法1
document.add_heading('Heading 1', level=1) # 用level設(shè)置,level為0-5,對(duì)應(yīng)不同級(jí)別的標(biāo)題
# 方法2
document.add_paragraph('Heading 1', style="Heading 1") # 用style來設(shè)置不同級(jí)別的標(biāo)題
3. 插入段落
段落是word文檔中最基本的對(duì)象之一。插入段落主要使用的函數(shù)是:add_paragraph() #添加段落
add_run() #追加文字
#插入段落, 同時(shí)設(shè)置粗體和斜體~
p = document.add_paragraph('A plain paragraph having some ')
p.add_run('bold').bold = True #粗體
p.add_run(' and some ')
p.add_run('italic.').italic = True #斜體
段落還可以使用style設(shè)置風(fēng)格。
# 圓點(diǎn)列表
document.add_paragraph(
'first item in unordered list', style='List Bullet'
)
# 序號(hào)列表
document.add_paragraph(
'first item in ordered list', style='List Number'
)
# 引用
document.add_paragraph('Intense quote', style='Intense Quote')
4 插入圖片
from docx.shared import Inches
document.add_picture('image-filename.png', width=Inches(1.0))
5 分頁符
document.add_page_break()
6 插入表格
主要使用的函數(shù):add_table() # 新建表格
add_row() # 添加行
add_col() # 添加列
table.cell(i, j).text() # 往表格中添加內(nèi)容
table.rows() # 行數(shù)
table.cols() # 列數(shù)
records = (
(3, '101', 'Spam'),
(7, '422', 'Eggs'),
(4, '631', 'Spam, spam, eggs, and spam')
)
# 新建1行3列的表
table = document.add_table(rows=1, cols=3) # row行, col列
# 使用table 的rows()和columns()得到這個(gè)表格的行數(shù)和列數(shù)
print(len(table.rows))
print(len(table.columns))
# 添加標(biāo)題行
hdr_cells = table.rows[0].cells # 注意 table.rows(0)表示第1行
hdr_cells[0].text = 'Qty'
hdr_cells[1].text = 'Id'
hdr_cells[2].text = 'Desc'
# 將records中的數(shù)據(jù)添加到新建的table中
for qty, id, desc in records:
row_cells = table.add_row().cells
row_cells[0].text = str(qty)
row_cells[1].text = id
row_cells[2].text = desc
如果熟悉pandas,那你肯定知道創(chuàng)建的dataframe默認(rèn)會(huì)自帶標(biāo)題行。但是python-docx不同,需要自行添加標(biāo)題行。這里要注意一下,不過別緊張不需要死記硬背,出現(xiàn)問題多調(diào)試就行~
7 保存文件
document.save(path) # 指定路徑
二、 做題!
至此,官方文檔的示例學(xué)的差不多了,基本上就是對(duì)標(biāo)題、段落、表格和圖片的處理。
下面來做一個(gè)簡單的題目:創(chuàng)建一個(gè)docx文件,要求輸入2個(gè)三行七列的三線表。
表格1:標(biāo)題欄為數(shù)字1到7。表格前有相應(yīng)標(biāo)題“1. 表格1”,標(biāo)題的字體為等線,且為斜體。
表格2:標(biāo)題欄為大寫字母A到G。表格前有相應(yīng)標(biāo)題“2. 表格2”, 標(biāo)題的字號(hào)為12,且為粗體。
希望你先自己寫一下,有問題多搜索。然后再來看看我的答案,對(duì)比下思路的不同。這樣學(xué)的更快,有問題也可以互相交流學(xué)習(xí)~
實(shí)現(xiàn)代碼:
#!/bin/usr/env python
from docx import Document
from docx.shared import Pt # 設(shè)置字號(hào)
document = Document()
# 表格1
# 標(biāo)題1,字體為等線,且為斜體
title1 = document.add_heading(u'1.表格1', level=1)
title1.style.font.name = u'等線' # 設(shè)置中文字體前面要有u
title1.italic = True
table1 = document.add_table(rows=3,cols=7) # 3行7列
# 設(shè)置表格標(biāo)題欄
for i in range(7):
table1.cell(0,i).text = str(i+1)
table1.style="Light Shading" # 風(fēng)格為三線表
# 表格2
# 標(biāo)題2,字號(hào)為12,且為粗體
title2 = document.add_paragraph(u'2.表格2',style="heading 1")
title2.style.font.size = Pt(12)
title2.bold = True
table2 = document.add_table(rows=3,cols=7) # 3行7列
headLine = ["A","B","C","D","E","F","G"]
# 設(shè)置表格標(biāo)題欄
for i in range(7):
table2.cell(0,i).text = headLine[i]
table2.style="Light Shading" # 風(fēng)格為三線表
# 儲(chǔ)存
document.save("test.docx")
最終結(jié)果↓ :
三、進(jìn)階
3.1 表格樣式模板:
其中常用的有Light Shading(三線表)↓ :
Table Grid(網(wǎng)格型)↓ :
Light Grid(淺色網(wǎng)格)↓ :
Medium List 1(中等深淺列表1) ↓:
Medium List 2(中等深淺列表2) ↓ :
可以點(diǎn)擊查看 python---word表格樣式設(shè)置. 蝸v牛. CSDN 查看更多樣式示例。但是現(xiàn)在的Python-docx包代碼有些更新,樣式和該鏈接中的圖例部分有出入。使用時(shí)需要自行調(diào)試~
3.2 自定義表格樣式
先試試下面的代碼~
from docx import Document # 輸出docx
from docx.shared import Pt # 設(shè)置字號(hào)
from docx.shared import Cm # 設(shè)置寬度,單位是cm
from docx.shared import RGBColor # 設(shè)置字體顏色
document = Document()
table = document.add_table(6,2, style="Normal Table")
colHeadLine = ["A","B","C","D","E","F"]
for i in range(6):
# 給單元格賦值的同時(shí)修改樣式,不影響整個(gè)表格
cell = table.cell(i,0)
cell.width = Cm(2) # 設(shè)置單元格寬度為2cm
run = cell.paragraphs[0].add_run(colHeadLine[i])
run.font.color.rgb = RGBColor(0,100,0)
run.font.name = u'等線'
run.italic = True
table.columns[0].width=Cm(3)
# 修改整個(gè)表格的字體樣式
table.style.font.size = Pt(10)
# 保存
document.save("test.docx")
3.2.1 表格自動(dòng)適應(yīng)窗口大小:
table.autofit = True
3.2.2 自定義表格寬度或高度:
a. 方法1:
table.cell(row,col).width = Cm(4) #
table.cell(row,col).height = Cm(4)
b. 方法2:
特別需要注意的是,column和row后面是有s的!
官方文檔中有無s標(biāo)注錯(cuò)誤,害得我還以為不能這樣操作,捂臉.jpg。
table.columns[0].width=Cm(2) # 不起效,不知道為什么
table.rows[0].height=Cm(2) # 起效
3.2.3 對(duì)齊
a. 表格對(duì)齊:
table.alignment = WD_TABLE_ALIGNMENT.CENTER #居中
table.alignment = WD_TABLE_ALIGNMENT.LEFT #靠左
table.alignment = WD_TABLE_ALIGNMENT.RIGHT #靠右
b. 文字對(duì)齊:
# 水平方向
table.cell(row,col).paragraphs[0].paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER
table.cell(row,col).paragraphs[0].paragraph_format.alignment = WD_ALIGN_PARAGRAPH.LEFT
table.cell(row,col).paragraphs[0].paragraph_format.alignment = WD_ALIGN_PARAGRAPH.RIGHT
# 垂直方向
table.cell(row,col).vertical_alignment = WD_ALIGN_VERTICAL.CENTER
table.cell(row,col).vertical_alignment = WD_ALIGN_VERTICAL.TOP
table.cell(row,col).vertical_alignment = WD_ALIGN_VERTICAL.BOTTOM
3.3 add_run() 設(shè)置字體、字號(hào)和顏色
from docx import Document
from docx.shared import Pt # 設(shè)置字號(hào)
from docx.shared import RGBColor # 設(shè)置字體顏色
document = Document()
p = document.add_paragraph('A plain paragraph')
run = p.add_run(' is plain') # 注意is之前的空格
run.font.name = u'等線' #設(shè)置字體
run.font.size = Pt(10.5) # 設(shè)置字號(hào)
run.font.color.rgb = RGBColor(250,0,0) # 設(shè)置字體顏色
# 保存
document.save("test.docx")3.3 結(jié)果
3.4 結(jié)合pandas的iloc函數(shù),將dataframe寫入word
import pandas as pd
from docx import Document # 輸出docx
from docx.shared import Pt # 設(shè)置字號(hào)
document = Document()
df = pd.read_csv(a.csv, sep="\t")
rowNum = df.shape[0] + 1 # 行數(shù),加標(biāo)題欄
colNum = df.shape[1] # 列數(shù)
table = document.add_table(rows=rowNum, cols=colNum, style = "Light Grid")
table.cell(0,0).text = "a"
table.cell(0,1).text = "b"
table.cell(0,2).text = "c"
table.cell(0,3).text = "d"
for i in range(1, rowNum):
for j in range(colNum):
cell = table.cell(i,j)
cell.text = str(df.iloc[i-1,j])
table.autofit = True
table.style.font.name = u'等線'
table.style.font.size = Pt(12)
document.save(outPutDocx)
一個(gè)示例 ↓ :
四、總結(jié)如何創(chuàng)建和讀取文檔
插入標(biāo)題、段落、圖片、分頁符和表格
進(jìn)階學(xué)習(xí),表格和段落的字體、字號(hào)、顏色的處理
后續(xù)如果發(fā)現(xiàn)更多有趣的用法,也會(huì)更新本文~
覺得有用別忘記點(diǎn)贊呀~
感謝O(∩_∩)O~
以上!
:梨醬:[論文寫作 1] 如何用word批量制作三線表??zhuanlan.zhihu.com梨醬:[Linux 1] Shell“ 多線程”,提高工作效率?zhuanlan.zhihu.com梨醬:[生信資料 3] 生物信息學(xué)常見數(shù)據(jù)格式,匯總!?zhuanlan.zhihu.com
參考:
創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎(jiǎng)勵(lì)來咯,堅(jiān)持創(chuàng)作打卡瓜分現(xiàn)金大獎(jiǎng)總結(jié)
以上是生活随笔為你收集整理的python docx包_[Python02] Python-docx包的使用,快速处理 Word 文件!的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: winform响应时间最长是多少分钟_当
- 下一篇: ab的plc跟西门子哪个好些_2020滚