安裝模塊
# Word操作庫
pip install docx
# Excel操作庫
pip install openpyxl
# 打包exe工具
pip install pyinstaller
Word操作
參考地址:https://python-docx.readthedocs.io/en/latest/
-
注意事項
- 只能對openxml規格的docx格式操作
-
Word內部結構
# 有時候通過公開的方法無法取到數據時,可以考慮用內部的xml結構處理
from docx import Document
doc= Document(path)
body_element = doc._body._body
# 顯示文檔內部結構
print(body_element.xml)
- 實例:獲取文檔目錄
#獲取xml的命名空間
def xpath_ns(tree):
"get xml namespace"
nsmap = dict((k, v) for k, v in tree.nsmap.items() if k)
return nsmap
doc= Document(path)
body_element = doc._body._body
ns= xpath_ns(body_element)
# 獲取目錄所在節點
links = body_element.xpath('./w:p/w:hyperlink')
for link in links:
# 獲取每一條目錄的內容
runs= [Run(r,None) for r in link.xpath('w:r[@w:rsidRPr]',namespaces=ns)]
for r in runs:
# 打印內容
print(r.text)
- 實例:讀取表格內容
doc= Document(path)
for table in doc.tables:
for row in table.rows:
for cell in row.cells:
print(cell.text)
- 實例:讀取段落內容
doc= Document(path)
for g in doc.paragraphs:
for run in g.runs:
print(run.text)
Excel操作
參考地址:https://openpyxl.readthedocs.io/en/stable/usage.html
- 實例:格式設置
import openpyxl
from openpyxl.styles import PatternFill, Border, Side, Alignment,Font
# 單元格字體
bft=Font(name="Meiryo UI",size=9,bold=True)
# 填充樣式
headFill=PatternFill("solid", fgColor="d9d9d9")
# 邊框線
thin = Side(border_style="thin", color="000000")
# 邊框填充樣式
border= Border(top=thin, left=thin, right=thin, bottom=thin)
# 對齊方式
align= Alignment(horizontal="center", vertical="center")
# 改行設置
wraptext= Alignment(vertical="center",wrapText=True)
bk= openpyxl.load_workbook(filename="test.xlsx")
oSheet=bk["test"]
# Value設置數據
cell=oSheet.cell(row=row,column=col,value="hello world!")
cell.font=bft
cell.fill= headFill
cell.border= border
cell.alignment= align
#cell.alignment= wraptext
# 固定頭三行三列
oSheet.freeze_panes='D4'
bk.save(expath)
bk.close()
- 實例:自動列寬
原理就是獲取每列最大寬進行設置
import openpyxl
def getMaxLength(max,data):
"比較字符個數返回最大值"
length=len(str(data))
if length > max:
return length
else:
return max
book= openpyxl.load_workbook(filename="test.xlsx")
sheet=book["test"]
for col in sheet.columns:
max_length=0
for cell in col:
max_length=getMaxLength(max_length,cell.value)
adjusted_width = (max_length + 2) * 1.2
sheet.column_dimensions[col[0].column_letter].width = adjusted_width
打包exe文件
打包目的:在沒有python環境的電腦上也可以運行我們的程序
- cmd到py文件目錄
- 確認已經安裝pyinstaller
- 執行打包
PyInstaller test.py --onefile --noconsole
- --onefile: 表示打包成一個exe文件
- --noconsole:表示不顯示黑色命令窗口
-
執行之后會在目錄下生成dist與build文件夾
dist:文件夾里面的exe文件就是我們需要的exe。
現在在沒有Python環境的電腦也可以執行了。
其他操作
- 獲取文件夾文件
import glob
files= glob.glob(docxPath+"/*.docx")
- 字符串匹配替換
import re
re.sub(r'^[0-9,.]*', "", text)
- 獲取文件名稱
import ntpath
name=ntpath.basename(path)
- 判斷路徑是否為文件
from os.path import isfile
isfile(path)