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