0
0
PythonHow-ToBeginner · 3 min read

How to Write Excel File in Python Easily

To write an Excel file in Python, use the openpyxl library. Create a workbook, add data to cells, and save the file with workbook.save('filename.xlsx').
📐

Syntax

Here is the basic syntax to write an Excel file using openpyxl:

  • Workbook(): Creates a new Excel workbook.
  • active: Gets the active worksheet to work on.
  • cell(row, column, value): Writes a value to a specific cell.
  • save(filename): Saves the workbook to a file.
python
from openpyxl import Workbook

wb = Workbook()  # Create a new workbook
ws = wb.active   # Get the active worksheet
ws.cell(row=1, column=1, value='Hello')  # Write 'Hello' to cell A1
wb.save('example.xlsx')  # Save the workbook
💻

Example

This example creates an Excel file named example.xlsx with some text and numbers in different cells.

python
from openpyxl import Workbook

wb = Workbook()
ws = wb.active

# Write text and numbers
ws['A1'] = 'Name'
ws['B1'] = 'Age'
ws['A2'] = 'Alice'
ws['B2'] = 30
ws['A3'] = 'Bob'
ws['B3'] = 25

wb.save('example.xlsx')
Output
No output printed, but file 'example.xlsx' is created with the data.
⚠️

Common Pitfalls

Common mistakes when writing Excel files in Python include:

  • Not installing openpyxl before use (pip install openpyxl).
  • Forgetting to save the workbook after writing data.
  • Using incorrect cell references or row/column numbers.
  • Trying to write to a file that is open in Excel, which locks the file.
python
from openpyxl import Workbook

wb = Workbook()
ws = wb.active

# Wrong: Forgetting to save
ws['A1'] = 'Test'

# Correct:
wb.save('test.xlsx')
📊

Quick Reference

ActionCode Example
Create workbookwb = Workbook()
Get active sheetws = wb.active
Write to cellws['A1'] = 'Hello' or ws.cell(row=1, column=1, value='Hello')
Save filewb.save('file.xlsx')

Key Takeaways

Use the openpyxl library to write Excel files in Python.
Always save the workbook after adding data to write changes to disk.
Use correct cell references like 'A1' or row and column numbers.
Install openpyxl with pip before running your code.
Close the Excel file if open to avoid file access errors.