Reputation: 143
I am trying to write a list to a row in Python using openpyxl, but to no avail.
The list contains say for example ten values. I need to open an existing worksheet, and write those ten values to their own cell, along one row.
I need to use openpyxl due to its functionality of overwriting existing worksheets compared to xlsxwriter where you can only create new worksheets.
Upvotes: 5
Views: 34334
Reputation: 589
import openpyxl as xl
wb = xl.Workbook()
ws = wb.active
mylist = ['dog', 'cat', 'fish', 'bird']
ws.append(mylist)
wb.save('myFile.xlsx')
wb.close()
Upvotes: 3
Reputation: 71
I made a function for you. I have it in a "openpyxlutils" file on my computer. It allows you to put either the starting row letter or number (but the letter can't be like AA or BB).
def write_row(write_sheet, row_num: int, starting_column: str or int, write_values: list):
if isinstance(starting_column, str):
starting_column = ord(starting_column.lower()) - 96
for i, value in enumerate(write_values):
write_sheet.cell(row_num, starting_column + i, value)
Upvotes: 2
Reputation: 976
Have a look here, scroll down to the heading Writing Values to Cells.
TLDR:
>>> import openpyxl
>>> wb = openpyxl.Workbook()
>>> sheet = wb['Sheet']
>>> sheet['A1'] = 'Hello world!'
>>> sheet['A1'].value
'Hello world!
or if you prefer
sheet.cell(row=2, column=3).value = 'hello world'
Update: changed to wb['Sheet'] syntax as per @charlieclark comment, thx
Update: To write mylist into row 2
for col, val in enumerate(mylist, start=1):
sheet.cell(row=2, column=col).value = val
Upvotes: 9