我已使用日歷模塊將當月的日期保存在串列中。我希望將日期(又名專案)顯示在我創建的 Excel 檔案中。

在我的代碼中,我使用 for 回圈來遍歷指定范圍的單元格,并在每隔一行插入當前月份的日期。
# Importing classes from modules
from openpyxl import Workbook
from openpyxl import load_workbook
from openpyxl.utils import get_column_letter
import datetime
import calendar
# Creating a workbook
dest_filename = r"C:\Users\abbas\OneDrive\Desktop\Prog\Flex\Working houres.xlsx"
wb = load_workbook(dest_filename)
ws = wb.active
ws.title = "Working hours"
# Current date
ws["B1"] = datetime.datetime.now().strftime("%Y")
ws["C1"] = datetime.datetime.now().strftime("%b")
ws["E1"] = datetime.datetime.now().strftime("%a")
#days_in_the_month = calendar.monthcalendar(2022,5)
days_in_the_month = list(calendar.Calendar(firstweekday=0).monthdayscalendar(2022, 5))
cell_range = ws.iter_rows(min_row=4, max_row=15, min_col=2, max_col=8)
for rows in cell_range:
for cell in rows:
if cell.value is None:
cell.value = days_in_the_month[cell]
elif cell.value is not None:
continue
wb.save("Working hours.xlsx")
有人可以向我解釋一下如何將串列 days_of_the_month 中的日期插入到第 4、6、8、10、12 和 14 行的單元格中嗎?
還有這個錯誤意味著什么:
cell.value = days_in_the_month[cell]
TypeError: list indices must be integers or slices, not Cell
我一直在嘗試理解嵌套回圈并反復試驗,以了解為什么我無法在沒有成功的情況下解決這個問題。
uj5u.com熱心網友回復:
由于cell不是整數,因此當您嘗試訪問串列中的索引時,這不是一個有效的陳述句。
我認為是這樣的:
for rows in cell_range:
for cell in rows:
if cell.row % 2 == 0:
cell.value = days_in_the_month[(cell.row // 2) - 4][cell.column - 2] # Subtracting 4 and 2 from rows and cols as they are the starting offsets.
應該做的伎倆。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/479862.html
