How To Write To Excel In Python Using Openpyxl

In this tutorial, we will learn how to write to Excel files in Python using the popular library openpyxl. This library allows you to interact with Excel files such as reading, writing, and creating new workbooks in a simple and efficient manner.

Step 1: Installing openpyxl

To get started, we first need to install the openpyxl library. You can do this using the following command:

Step 2: Creating a Workbook

In order to write data to an Excel file, we need to create a workbook. A workbook is simply an Excel file that contains one or more sheets. With openpyxl, you can create a new workbook using the Workbook() class.

When you run this code, it will create a new Excel file named example.xlsx in the same directory as your Python script.

Step 3: Adding Data to a Worksheet

To add data to an Excel sheet, we first need to access the sheet we want to write to. By default, a new workbook created with openpyxl contains a single sheet named Sheet. You can access this sheet using the active property of the workbook.

You can also add data to the sheet using the cell() method, which takes row and column numbers as arguments. For example:

Step 4: Adding Rows and Columns

In many cases, you will want to write multiple rows or columns of data to the sheet. You can do this easily using the append() method, which takes a list of values as input and adds a new row to the sheet.

Step 5: Changing Worksheet Properties

Before we conclude, let’s explore how to change some basic properties of the worksheet such as its name, and column widths.

The Full Code:

Conclusion

In this tutorial, we have learned how to create, write, and modify Excel files in Python using the openpyxl library. With this library, you can easily manipulate workbooks, sheets, and data in a simple and efficient way. You can even use openpyxl to apply formatting, generate charts, and more to create professional-looking Excel files programmatically. Happy coding!