Home > database >  Append list to a row
Append list to a row

Time:01-12

I have List Called my_list have series of No I want add that no to a excel's perticuler row

  1. I want list's No start from E2 to len(my_list)
  2. And row is a single and start from E2 to AH2
  3. elements will place in E2 to AH2 likewise image

Click On Here To see Image

wb = load_workbook("Myworkbook.xlsx")
ws = wb.active
my_list=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31]

for rw in ws['E2:AH2']:
    for cell in rw:
        for c in my_list:
            cell.value = c


wb.save('Myworkbook.xlsx')

But In this way I just get last element of list like in image it gives only 31 but i want 1 to 31 in range and append in particularly in that single row

Click On Here To See image

CodePudding user response:

This is because your last loop (over my_list) goes through the entire list, up to 31, for each cell of your row. That's why you end up with the last value in every cell. You have nested this loop too deep.

What you actually want is go through each cell and value at the same time. Simplest way to achieve that is to zip both lists together and loop over that.

wb = load_workbook("Myworkbook.xlsx")
ws = wb.active
my_list=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31]

for rw in ws['E2:AH2']:
    for cell, c in zip(rw, my_list):
        cell.value = c


wb.save('Myworkbook.xlsx')

CodePudding user response:

In your case for each cell the my_list is traversed to the end (by innermost for loop) having each cell assigned with last value, while it's needed to map cells and my_list values pairwise:

To fix that you can apply the following:

for row in ws['E2:AH2']:
    for i, cell in enumerate(row):
        cell.value = my_list[i]
  • Related