轉載請注明:陳熹 chenx6542@foxmail.com (簡書號:半為花間酒)
若公眾號內轉載請聯系公眾號:早起Python這篇文章能學到的主要內容:
openpyxl
讀取Excel獲取內容docx
讀寫word文件能學到的小技巧:
os
獲取桌面路徑win32com
批量doc轉換為docx(僅windows用戶)(文末附原始數據文件下載鏈接)
今天早起python
公眾號的讀者提出了一個需求:
(由于涉及文件私密所以具體內容已做修改)
每一列的數據需要按照一定規則填到一個word模板里,規則和模板大致如下:
這些是需要填寫的部分,整體的模板要復雜一些:
還有一個需求:最終輸出的word文件命名如下:
C列的數據去重然后用&鏈接 + G2 + V列數據求和 + P列的數據去重后用&連接 + 當天日期(如:2020年04月22日) + 驗貨報告
從需求和文件格式上看,這次文件的讀寫解析任務較復雜,碼代碼和思考時間會較久,因此需要想清楚一個問題:
這次需要完成的任務是否工作量很多,或者以后長期需要進行,用python可以解放雙手?
如果不是,實際上手動就可以完成,失去了自動化辦公的意義
ok接下來我們正式碼代碼
1. 解析Excel的數據
將原始數據解壓縮后文件夾放在桌面即可
當然如果你想放其他地方也可以,就指名絕對路徑
from openpyxl import load_workbook
import os
# 獲取桌面的路徑
def GetDesktopPath():
return os.path.join(os.path.expanduser("~"), 'Desktop')
path = GetDesktopPath() + '/資料/' # 形成文件夾的路徑便后續重復使用
workbook = load_workbook(filename=path + '數據.xlsx')
sheet = workbook.active # 獲取當前頁
# 可以用代碼獲取數據范圍,如果要批處理循環迭代也方便
# 獲取有數據范圍
print(sheet.dimensions)
# A1:W10
利用openpyxl
讀取單元格有以下幾種用法:
cells = sheet['A1:A4'] # 返回A1-A4的4個單元格
cells = sheet['A'] # 獲取A列
cells = sheet['A:C'] # 獲取A-C列
cells = sheet[5] # 獲取第5行
# 注意如果是上述用cells獲取返回的是嵌套元祖
for cell in cells:
print(cell[0].value) # 遍歷cells依然需要取出元祖中元素才可以獲取值
# 獲取一個范圍的所有cell
# 也可以用iter_col返回列
for row in sheet.iter_rows(min_row=1, max_row=3,
min_col=2, max_col=4):
for cell in row:
print(cell.value)
明白了原理我們就可以解析獲取Excel中的數據了
# SQE
SQE = sheet['Q2'].value
# 供應商&制造商
supplier = sheet['G2'].value
# 采購單號
C2_10 = sheet['C2:C10'] # 返回cell.tuple對象
# 利用列表推導式后面同理
vC2_10 = [str(cell[0].value) for cell in C2_10]
# 用set簡易去重后用,連接,填word表用
order_num = ','.join(set(vC2_10))
# 用set簡易去重后用&連接,word文件名命名使用
order_num_title = '&'.join(set(vC2_10))
# 產品型號
T2_10 = sheet['T2:T10']
vT2_10 = [str(cell[0].value) for cell in T2_10]
ptype = ','.join(set(vT2_10))
# 產品描述
P2_10 = sheet['P2:P10']
vP2_10 = [str(cell[0].value) for cell in P2_10]
info = ','.join(set(vP2_10))
info_title = '&'.join(set(vP2_10))
# 日期
# 用datetime庫獲取今日時間以及相應格式化
import datetime
today = datetime.datetime.today()
time = today.strftime('%Y年%m月%d日')
# 驗貨數量
V2_10 = sheet['V2:V10']
vV2_10 = [int(cell[0].value) for cell in V2_10]
total_num = sum(vV2_10) # 計算總數量
# 驗貨箱數
W2_10 = sheet['W2:W10']
vW2_10 = [int(cell[0].value) for cell in W2_10]
box_num = sum(vW2_10)
# 生成最終需要的word文件名
title = f'{order_num_title}-{supplier}-{total_num}-{info_title}-{time}-驗貨報告'
print(title)
Excel的部分就結束了,接下來進行word的填表啦
這里我們默認讀取的word是.docx
格式的,實際上讀者的需求是.doc
格式文件
這里如果是windows用戶可以用如下代碼批量轉化doc,前提是安裝好win32com
# pip install pypiwin32
from win32com import client
docx_path = path + '模板.docx'
# doc轉docx的函數
def doc2docx(doc_path,docx_path):
word = client.Dispatch("Word.Application")
doc = word.Documents.Open(doc_path)
doc.SaveAs(docx_path, 16)
doc.Close()
word.Quit()
print('\n doc文件已轉換為docx \n')
if not os.path.exists(docx_path):
doc2docx(docx_path[:-1], docx_path)
Mac暫時沒有好的解決策略,如果有思路歡迎交流
有docx
格式文件后我們繼續操作
docx_path = path + '模板.docx'
from docx import Document
# 實例化
document = Document(docx_path)
# 讀取word中的所有表格
tables = document.tables
# print(len(tables))
# 15
確定好每個表格數后即可進行相應的填報操作
table的用法和openpyxl
中非常類似,注意索引和原生python一樣都是從0開始
tables[0].cell(1, 1).text = SQE
tables[1].cell(1, 1).text = supplier
tables[1].cell(2, 1).text = supplier
tables[1].cell(3, 1).text = ptype
tables[1].cell(4, 1).text = info
tables[1].cell(5, 1).text = order_num
tables[1].cell(7, 1).text = time
for i in range(2, 11):
tables[6].cell(i, 0).text = str(sheet[f'T{i}'].value)
tables[6].cell(i, 1).text = str(sheet[f'P{i}'].value)
tables[6].cell(i, 2).text = str(sheet[f'C{i}'].value)
tables[6].cell(i, 4).text = str(sheet[f'V{i}'].value)
tables[6].cell(i, 5).text = str(sheet[f'V{i}'].value)
tables[6].cell(i, 6).text = '0'
tables[6].cell(i, 7).text = str(sheet[f'W{i}'].value)
tables[6].cell(i, 8).text = '0'
tables[6].cell(12, 4).text = str(total_num)
tables[6].cell(12, 5).text = str(total_num)
tables[6].cell(12, 7).text = str(box_num)
這里有兩個細節:
- word寫入的數據需是字符串,所以從Excel獲取的數據需要用str格式化
- 這個也是最耗費精力和時間的,表格可能存在合并等其他情況,因此你看到的行數和列數可能不是真實的,需要用代碼不斷測試。上述代碼中跳過了第4列,試一試為什么
for i in range(2, 11):
tables[13].cell(i - 1, 0).text = str(sheet[f'T{i}'].value)
tables[13].cell(i - 1, 1).text = str(sheet[f'U{i}'].value)
tables[13].cell(i - 1, 2).text = str(sheet[f'U{i}'].value)
tables[13].cell(i - 1, 3).text = str(sheet[f'U{i}'].value)
需求大致就完成了,記得保存
document.save(path + f'{title}.docx')
print('\n文件已生成')
最后附上完整代碼
from openpyxl import load_workbook
from docx import Document
import datetime
# pip install pypiwin32
# from win32com import client
import os
# 獲取桌面的路徑
def GetDesktopPath():
return os.path.join(os.path.expanduser("~"), 'Desktop')
path = GetDesktopPath() + '/資料/' # 形成文件夾的路徑便后續重復使用
workbook = load_workbook(filename=path + '數據.xlsx')
sheet = workbook.active # 獲取當前頁
# 獲取有數據范圍
# print(sheet.dimensions)
# A1:W10
# SQE
SQE = sheet['Q2'].value
# 供應商&制造商
supplier = sheet['G2'].value
# 采購單號
C2_10 = sheet['C2:C10'] # 返回cell.tuple對象
vC2_10 = [str(cell[0].value) for cell in C2_10]
order_num = ','.join(set(vC2_10))
order_num_title = '&'.join(set(vC2_10))
# 產品型號
T2_10 = sheet['T2:T10']
vT2_10 = [str(cell[0].value) for cell in T2_10]
ptype = ','.join(set(vT2_10))
# 產品描述
P2_10 = sheet['P2:P10']
vP2_10 = [str(cell[0].value) for cell in P2_10]
info = ','.join(set(vP2_10))
info_title = '&'.join(set(vP2_10))
# 日期
today = datetime.datetime.today()
time = today.strftime('%Y年%m月%d日')
# 驗貨數量
V2_10 = sheet['V2:V10']
vV2_10 = [int(cell[0].value) for cell in V2_10]
total_num = sum(vV2_10) # 計算總數量
# 驗貨箱數
W2_10 = sheet['W2:W10']
vW2_10 = [int(cell[0].value) for cell in W2_10]
box_num = sum(vW2_10)
title = f'{order_num_title}-{supplier}-{total_num}-{info_title}-{time}-驗貨報告'
print(title)
doc_path = path + '模板.docx'
docx_path = doc_path + 'x'
# doc轉docx的函數
# def doc2docx(doc_path,docx_path):
# word = client.Dispatch("Word.Application")
# doc = word.Documents.Open(doc_path)
# doc.SaveAs(docx_path, 16)
# doc.Close()
# word.Quit()
# print('\n doc文件已轉換為docx \n')
# if not os.path.exists(docx_path):
# doc2docx(doc_path, docx_path)
document = Document(docx_path)
# 讀取word中的所有表格
tables = document.tables
# print(len(tables))
# 15
# 開始填表
tables[0].cell(1, 1).text = SQE
tables[1].cell(1, 1).text = supplier
tables[1].cell(2, 1).text = supplier
tables[1].cell(3, 1).text = ptype
tables[1].cell(4, 1).text = info
tables[1].cell(5, 1).text = order_num
tables[1].cell(7, 1).text = time
for i in range(2, 11):
tables[6].cell(i, 0).text = str(sheet[f'T{i}'].value)
tables[6].cell(i, 1).text = str(sheet[f'P{i}'].value)
tables[6].cell(i, 2).text = str(sheet[f'C{i}'].value)
tables[6].cell(i, 4).text = str(sheet[f'V{i}'].value)
tables[6].cell(i, 5).text = str(sheet[f'V{i}'].value)
tables[6].cell(i, 6).text = '0'
tables[6].cell(i, 7).text = str(sheet[f'W{i}'].value)
tables[6].cell(i, 8).text = '0'
tables[6].cell(12, 4).text = str(total_num)
tables[6].cell(12, 5).text = str(total_num)
tables[6].cell(12, 7).text = str(box_num)
for i in range(2, 11):
tables[13].cell(i - 1, 0).text = str(sheet[f'T{i}'].value)
tables[13].cell(i - 1, 1).text = str(sheet[f'U{i}'].value)
tables[13].cell(i - 1, 2).text = str(sheet[f'U{i}'].value)
tables[13].cell(i - 1, 3).text = str(sheet[f'U{i}'].value)
document.save(path + f'{title}.docx')
print('文件已生成')
寫在最后
如果有感興趣的自動化辦公方向,或者手上有具體的案例想利用python解決
歡迎與我交流,或者直接在公眾號早起python
留言
我們會選取有意思的例子無償解決并發布教程分享經驗讓更多人獲益
如果要提供案例需要說清楚需求,以及提供處理過的原始數據
我們發布教程前會對數據進行無害化處理的哈哈哈哈保護隱私
原數據下載:
https://pan.baidu.com/s/1YFZPT7KViB5O-oQe4y_6HQ
提取碼:ym7p