Writing to row using openpyxl?

Question:

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.

Asked By: user3328696

||

Answers:

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
Answered By: Steve

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)
import openpyxl as xl
wb = xl.Workbook()
ws = wb.active
mylist = ['dog', 'cat', 'fish', 'bird']
ws.append(mylist)
wb.save('myFile.xlsx')
wb.close()

enter image description here

Answered By: Mark Seagoe
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.