Python辦公自動化|從Excel到Word
更多自動化案例歡迎關注我的公眾號:早起Python
===
前言
在前幾天的文章中我們講解了如何從Word表格中提取指定資料並按照格式儲存到Excel中,今天我們將再次以一位讀者提出的真實需求來講解如何
使用Python從Excel中計算、整理資料並寫入Word
中,其實並不難,主要就是以下兩步:
openpyxl讀取Excel獲取內容
docx讀寫Word檔案
那我們開始吧!
需求確認
首先來看下我們需要處理的Excel部分資料,因涉及隱私已經將資料
皮卡丘化
可以看到資料非常多,並且還存在重複資料。而我們要做的就是對每一列的資料
按照一定的規則進行計算、整理並使用Python自動填入到Word中
,大致的要求如下
上面僅是部分要求,真實需要填入word中的資料要更多!
除了對按照格式進行處理並存入Word中指定位置之外,還有一個需求:最終輸出的word
檔名
還需要按照一定規則生成:
OK,需求分析完畢,接下來看
Python
如何解決!
Python實現
首先我們使用Python對該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中提取出來資料,這樣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格式檔案後我們繼續操作Word部分
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
上面程式碼完成Word中這一部分表格
我們繼續用Python填寫下一個表格
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格式化
表格可能存在合併等其他情況,因此你看到的行數和列數可能不是真實的,需要用程式碼不斷測試。
按照上面的辦法,將之前從Excel中取出來的資料一一填充到Word中對應位置就大功告成!最後儲存一下即可。
document。save(path + f‘{title}。docx’)
print(‘\n檔案已生成’)
結束語
回顧上面的過程,其實從需求和檔案格式上看,這次檔案的讀寫解析任務較複雜,碼程式碼和思考時間會較久,所以當我們在考慮使用Python進行辦公自動化之前需要想清楚這個問題:
這次需要完成的任務是否工作量很多,或者以後長期需要進行,用Python是否可以解放雙手
?如果不是,實際上手動就可以完成,那麼就失去了自動化辦公的意義!
注:本文使用的資料與原始碼可在早起Python內獲取