Python Excel

Openpyxl Write to a Cell

Writing one cell is three steps: import openpyxl, open or create a workbook, then pick the worksheet. After that, any of the three patterns below stores a value.

Prepare the worksheet

import openpyxl

wb = openpyxl.load_workbook("myfile.xlsx")
sheet = wb["Sheet1"]

If the file does not exist yet, create it instead:

wb = openpyxl.Workbook()
sheet = wb.active
sheet.title = "Sheet1"

1. Use the cell address

This is the clearest form when you know the address, such as B4 or F16.

sheet["B4"] = "We are writing to B4"

2. Keep a reference to the cell

cell = sheet["B4"]
cell.value = "Writing with a cell reference"

Assign to .value. Assigning a string to the cell variable itself replaces the cell object and does not change the worksheet.

3. Use row and column numbers

Excel column E is column 5. Row 4, column 5 is cell E4. Numbers are what you want inside a loop.

cell = sheet.cell(row=4, column=5)
cell.value = "Writing data to E4"

The same call can set the value immediately:

names = ["Ana", "Ben", "Cid", "Dia"]
for index, name in enumerate(names, start=5):
    sheet.cell(row=index, column=5, value=name)

wb.save("myfile.xlsx")

The loop writes Ana into E5, Ben into E6, and so on. Save when the loop finishes. Until save, the changes exist only in memory.

Write a formula

A formula is a string that starts with =, the same way you would type it in Excel:

sheet["F6"] = "=SUM(D7:D20)"
wb.save("myfile.xlsx")

openpyxl stores the formula. Excel calculates it the next time the file is opened. See Python Excel Writer for fonts, column width, and merged cells.