OpenPyxl is a Python library that provides tools for reading, writing, and manipulating Excel files in the Excel 2010 format (which uses the .xlsx extension). This is a high-level library that abstracts away many low-level details, making it simple to work with spreadsheets programmatically.
Read and Write Excel Files: OpenPyxl can be used to both read from and write to .xlsx files.
Work with Cells: We can access, modify, and create new cells in Excel sheets.
Support for Formulas: OpenPyxl supports the evaluation of Excel formulas.
Styles and Formatting: We can modify the look and feel of cells (font, color, borders, etc.).
Charting: OpenPyxl also provides the ability to create simple charts in Excel files.
Working with Pivot Tables: Though limited, OpenPyxl offers the capability to interact with pivot tables.
Installing OpenPyxl
To use OpenPyxl, we'll first need to install it. We can do this using pip:
pip install openpyxl
Once installed, we're ready to start working with Excel files.
Basic Usage of OpenPyxl
1. Creating a New Excel File
Creating a new Excel file and saving it is quite straightforward with OpenPyxl. Hereβs how to create a basic Excel workbook and sheet:
Explanation:
Workbook() creates a new Excel file.
.active returns the default sheet.
.save() writes the file to disk.
2. Writing Data to an Excel File
Let's now populate the Excel sheet with some data: