[英]Creating a new sheet every month with openpyxl
嗨我參與納米比亞的旅游小屋。 我們記錄水讀數等。 每天輸入一個Excel文件並計算每個Pax的消耗量,問題不是每個員工都理解Excel。 所以我寫了一個簡單的Python程序,自動將讀數輸入到excel中。 它唯一的問題是我想在每個月保存一張新表並按月分組所有數據(例如1月(所有讀數)2月(所有讀數))。 我可以創建一個新工作表,但我無法將數據輸入到新工作表中,它只是覆蓋了前幾個月的數據...代碼如下所示
*import tkinter
from openpyxl import load_workbook
from openpyxl.styles import Font
import time
import datetime
book = load_workbook('sample.xlsx')
#sheet = book.active
Day = datetime.date.today().strftime("%B")
x = book.get_sheet_names()
list= x
if Day in list: # this checks if the sheet exists to stop the creation of multiple sheets with the same name
sheet = book.active
else:
book.create_sheet(Day)
sheet = book.active
#sheet = book.active*
並寫入我使用的工作表和條目小部件,然后保存值如下:
Bh1=int(Bh1In.get())
if Bh1 == '0':
import Error
else:
sheet.cell(row=Day , column =4).value = Bh1
number_format = 'Number'
也許我是傻瓜,但請幫助!
您依賴於獲取活動工作表而不是按名稱訪問它。 只需使用以下內容:
try:
sheet = wb[Day]
except KeyError:
sheet = wb.create_sheet(Day)
可能就是你所需要的一切。
嘗試
if Day in list: # this checks if the sheet exists to stop the creation of multiple sheets with the same name
sheet = book.get_sheet_by_name(Day)
else:
book.create_sheet(Day)
book.save('sample.xlsx')
sheet = book.get_sheet_by_name(Day)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.