In this tutorial, we will learn how to write data in Excel sheets using the Python library Openpyxl. The Openpyxl module allows Python to read, write and modify Excel files without any instance of Excel software.
Requirements
Before writing to an Excel file, we need to install the Openpyxl library. It’s a Python library for handling Excel files. If not already installed, you can install it by running the following command in your terminal:
1 |
pip install openpyxl |
Creating An Excel File
The first step in writing data to an Excel file involves creating a workbook and adding a worksheet to the workbook. A workbook is essentially the Excel file itself which can contain various worksheets specified by the user.
1 2 3 |
import openpyxl excel_file = openpyxl.Workbook() # creates a new workbook sheet = excel_file.active # gets the active worksheet |
Adding Data
To add data into the Excel file, you can use the cell method in your script and mention the cell’s coordinates in the method. For example, you can enter ‘Hello, World!’ in the first cell (A1) using the following code:
1 |
sheet['A1'] = 'Hello, World!' |
Saving The Excel File
After writing the necessary data in the Excel file, we need to save it using the save method to store data permanently. We name our Excel file ‘example.xlsx’.
1 |
excel_file.save('example.xlsx') |
The Full Python Code
1 2 3 4 5 6 7 8 9 10 11 |
import openpyxl # Creating a workbook and getting the active worksheet excel_file = openpyxl.Workbook() sheet = excel_file.active # Writing data in A1 cell sheet['A1'] = 'Hello, World!' # Saving the excel file excel_file.save('example.xlsx') |

Conclusion
Using the Openpyxl library, Python makes it straightforward and quick to handle Excel files. This is a readily applicable approach that can be applied to manipulate or access Excel data efficiently. Therefore, Openpyxl is an essential library when dealing with Excel files in Python.