Search code examples
pythonexcelcalendaropenpyxlnested-loops

How to insert items from list of list into excel cells using nested for loops?


I have saved the days in the current month in a list using the calendar module. I want the days (aka items) to be displayed in a excel file I've created.

enter image description here

In my code I'm using for loops in order to loop through a specified range of cells and insert the days of the current month in every second row.

# 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")

Can someone please explain to me how I can insert the days in the list days_of_the_month into the cells, in the rows 4, 6, 8, 10, 12 and 14?

And also what this error means:

    cell.value = days_in_the_month[cell]
TypeError: list indices must be integers or slices, not Cell

I've been trying to understand the nested loops and experimented back and forth in order to understand why I can't figure this out without success.


Solution

  • As cell is not an integer, this is not a valid statement as you are trying to access indices in a list.

    I think that something like:

    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.
    

    Should do the trick.