用python实现自动填数生成表格v1.0
生活随笔
收集整理的這篇文章主要介紹了
用python实现自动填数生成表格v1.0
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
先簡單描述一下需求,是這樣,有時候人事部門需要對著同樣的一張表錄入數據,比如說員工退休表,這樣的表通常是一張excel表格,由于退休員工有多個,那么這樣的表肯定就要經常錄入了。錄入之后由于excel是獨立分散的,并不便于后續的數據的查找、管理等。同時,每個退休員工都要錄入一張表的話,有時候工作量很大,也容易出錯。
這樣的業務需求其實是很多的,比如生成每個學生獨立的成績單等等。
那么,有沒有什么辦法比較好解決呢?當然是有,而且思路是很簡單的。首先先把所有待處理的數據填放在一個數據源的excel表格里面,再分別制作一個模板和一個填入位置的excel。然后用python去讀取數據源、模板和填入位置,然后復制模板并且按照填入位置用數據源表格里面的每一行表格逐一生成一個個的處理后的結果表即可了。
先上代碼:
from openpyxl import Workbook from openpyxl import load_workbook import os import datetime import shutildef now(year=True,month=True,day=True,hour=True,minute=True,second=True):def complete(x):return '0' + str(x) if x<10 else str(x)d = datetime.datetime.now()result = ''if year:result += str(d.year) + '-'if month:result += complete(d.month) + '-'if day:result += complete(d.day) + ' 'if hour:result += complete(d.hour) + '-'if minute:result += complete(d.minute) + '-'if second:result += complete(d.second) + '-'return result[:-1] path = os.getcwd()def run():print(now()+' 開始任務,請稍候...')if not os.path.exists(os.getcwd() + '\\' + '模板.xlsx'):print('丟失模板.xlsx,請設置好文件再運行...')returntemplate_name = os.getcwd() + '\\' + '模板.xlsx'if not os.path.exists(os.getcwd() + '\\' + '數據源.xlsx'):print('丟失模板.xlsx,請設置好文件再運行...')returndata_sheet = load_workbook(os.getcwd() + '\\' + '數據源.xlsx').activeif not os.path.exists(os.getcwd() + '\\' + '填入位置.xlsx'):print('丟失模板.xlsx,請設置好文件再運行...')returnlocation_sheet = load_workbook(os.getcwd() + '\\' + '填入位置.xlsx').activelc = []for column in range(1,location_sheet.max_column+1):lc.append(str(location_sheet.cell(2,column).value).upper())outputfolder = 'output ' + now()if not os.path.exists(os.getcwd() + '\\' + outputfolder):os.mkdir(os.getcwd() + '\\' + outputfolder)for row in range(2,data_sheet.max_row+1):targetname = os.getcwd() + '\\' + outputfolder + '\\' + str(data_sheet.cell(row,1).value) +'.xlsx'shutil.copy(template_name,targetname)target = load_workbook(targetname)target_sheet = target.activefor i in range(0,len(lc)):target_sheet[lc[i]] = data_sheet.cell(row,i+1).valuetarget.save(targetname)print(now()+' 任務完成...')# except:# print('您的模板、數據源、填入位置可能填寫有誤,出現異常了,請好好檢查再重新運行...')run() print('請輸入任意鍵退出...') input()demo文件在這里:https://download.csdn.net/download/sinolzeng/15432505
總結
以上是生活随笔為你收集整理的用python实现自动填数生成表格v1.0的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 用python结束exe进程
- 下一篇: 用python实现自动填数生成表格v2.