溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Python怎么從Excel中計(jì)算整理數(shù)據(jù)并寫入Word

發(fā)布時(shí)間:2022-07-01 09:53:56 來源:億速云 閱讀:411 作者:iii 欄目:開發(fā)技術(shù)

這篇文章主要介紹了Python怎么從Excel中計(jì)算整理數(shù)據(jù)并寫入Word的相關(guān)知識(shí),內(nèi)容詳細(xì)易懂,操作簡單快捷,具有一定借鑒價(jià)值,相信大家閱讀完這篇Python怎么從Excel中計(jì)算整理數(shù)據(jù)并寫入Word文章都會(huì)有所收獲,下面我們一起來看看吧。

Python實(shí)現(xiàn)

首先我們使用Python對(duì)該Excel進(jìn)行解析

from openpyxl import load_workbook
import os
# 獲取桌面的路徑
def GetDesktopPath():
    return os.path.join(os.path.expanduser("~"), 'Desktop')

path = GetDesktopPath() + '/資料/' # 形成文件夾的路徑便后續(xù)重復(fù)使用
workbook = load_workbook(filename=path + '數(shù)據(jù).xlsx')
sheet = workbook.active # 獲取當(dāng)前頁
# 可以用代碼獲取數(shù)據(jù)范圍,如果要批處理循環(huán)迭代也方便
# 獲取有數(shù)據(jù)范圍
print(sheet.dimensions)
# A1:W10

利用openpyxl讀取單元格有以下幾種用法

cells = sheet['A1:A4']  # 返回A1-A4的4個(gè)單元格
cells = sheet['A'] # 獲取A列
cells = sheet['A:C'] # 獲取A-C列
cells = sheet[5] # 獲取第5行
# 注意如果是上述用cells獲取返回的是嵌套元祖
for cell in cells:
    print(cell[0].value) # 遍歷cells依然需要取出元祖中元素才可以獲取值
# 獲取一個(gè)范圍的所有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中的數(shù)據(jù)了

# SQE
SQE = sheet['Q2'].value
# 供應(yīng)商&制造商
supplier = sheet['G2'].value
# 采購單號(hào)
C2_10 = sheet['C2:C10'] # 返回cell.tuple對(duì)象
# 利用列表推導(dǎo)式后面同理
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))
# 產(chǎn)品型號(hào)
T2_10 = sheet['T2:T10']
vT2_10 = [str(cell[0].value) for cell in T2_10]
ptype = ','.join(set(vT2_10))
# 產(chǎn)品描述
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庫獲取今日時(shí)間以及相應(yīng)格式化
import datetime
today = datetime.datetime.today()
time = today.strftime('%Y年%m月%d日')
# 驗(yàn)貨數(shù)量
V2_10 = sheet['V2:V10']
vV2_10 = [int(cell[0].value) for cell in V2_10]
total_num = sum(vV2_10) # 計(jì)算總數(shù)量
# 驗(yàn)貨箱數(shù)
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}-驗(yàn)貨報(bào)告'
print(title)

通過上面的代碼,我們就成功的從Excel中提取出來數(shù)據(jù),這樣Excel部分就結(jié)束了,接下來進(jìn)行word的填表啦,由于這里我們默認(rèn)讀取的word是.docx格式的,實(shí)際上讀者的需求是.doc格式文件,所以windows用戶可以用如下代碼批量轉(zhuǎn)化doc,前提是安裝好win32com

# pip install pypiwin32
from win32com import client
docx_path = path + '模板.docx'
# doc轉(zhuǎn)docx的函數(shù)
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文件已轉(zhuǎn)換為docx \n')
if not os.path.exists(docx_path):
    doc2docx(docx_path[:-1], docx_path)

不過在Mac下暫時(shí)沒有好的解決策略,如果有思路歡迎交流,好了有docx格式文件后我們繼續(xù)操作Word部分

docx_path = path + '模板.docx'
from docx import Document
# 實(shí)例化
document = Document(docx_path)
# 讀取word中的所有表格
tables = document.tables
# print(len(tables))
# 15

確定好每個(gè)表格數(shù)后即可進(jìn)行相應(yīng)的填報(bào)操作,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

我們繼續(xù)用Python填寫下一個(gè)表格

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)

這里需要注意兩個(gè)細(xì)節(jié):

  • word寫入的數(shù)據(jù)需是字符串,所以從Excel獲取的數(shù)據(jù)需要用str格式化

  • 表格可能存在合并等其他情況,因此你看到的行數(shù)和列數(shù)可能不是真實(shí)的,需要用代碼不斷測(cè)試。

按照上面的辦法,將之前從Excel中取出來的數(shù)據(jù)一一填充到Word中對(duì)應(yīng)位置就大功告成!最后保存一下即可。

document.save(path + f'{title}.docx')
print('\n文件已生成')

關(guān)于“Python怎么從Excel中計(jì)算整理數(shù)據(jù)并寫入Word”這篇文章的內(nèi)容就介紹到這里,感謝各位的閱讀!相信大家對(duì)“Python怎么從Excel中計(jì)算整理數(shù)據(jù)并寫入Word”知識(shí)都有一定的了解,大家如果還想學(xué)習(xí)更多知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI