-2

Using openpyxl i'm trying to insert a list naming a specific cell. here is my failed attempt

l1 = ["John", 1, 2, 3]

for i in l1:
    ws.cell(1,2).append(i)

wb.save("tentavive.xlsx")
ljmc
  • 4,830
  • 2
  • 7
  • 26

1 Answers1

0

Some points about openpyxl append

  1. understand that append inserts at the end of the sheet i.e. the next row after the current row with used cells. You cannot specifiy another row to insert at. If row 2 is the last row with data in any column then the append will be on row 3.
  2. the append starts from the first column (A) so if you want an append to start in another column the first elements in the list would have to be a blank so for 'John' to be inserted in column B pad the list, i.e.

l1 = ["", "John", 1, 2, 3]

  1. append accepts either list or a dictionary not a single value so iterating through the list is not required and will return an error
  2. append is a worksheet attribute so your line would return an error using as a cell attribute

ws.cell(1,2).append(i)

Therefore your code should be;

l1 = ["","John", 1, 2, 3]

ws.append(l1)

wb.save("tentavive.xlsx")

If you used a dictionary instead the same conditions as above apply except you could specify the column for each value to be placed in so its not necessary to pad, if 'John' is to be placed in column B then set the key to 'B'.

d1 = {'B':"John", 'C': 1, 'E': 2, 'F': 3}
ws.append(d1)

wb.save("tentavive.xlsx")

If you do want to specify which row/column to write the values in the list to, then dont use append. Something like this will do the trick

for enum, i in enumerate(l1, 2):
    ws.cell(1, enum).value = i

wb.save("tentavive.xlsx")
moken
  • 3,227
  • 8
  • 13
  • 23