Python is an incredible tool for automating tasks, and when combined with Excel, you’re able to access and manipulate data in a quick and easy manner. Today, we’ll be walking through how you can use Python to highlight a cell in Excel.
To successfully execute the steps mentioned here, you need to have Python installed on your local machine. If you have not installed Python yet, check out the official Python website to get started.
Step 1: Create an Excel File
Step 2: Importing the Library
Now that you’ve successfully installed openpyxl, you can import it into your Python script using the following command:
1 |
import openpyxl |
The next step is to make use of the methods provided by the openpyxl library to highlight a cell in Excel.
Step 3: Loading the Workbook
First, we need to load our Excel workbook into our script using the load_workbook method.
1 |
workbook = openpyxl.load_workbook('file.xlsx') |
Replace ‘file.xlsx’ with the path to your desired Excel file.
Step 4: Selecting the Sheet and Cell
Next, select the sheet you want to work with. Afterward, select the cell that you want to highlight.
1 2 |
sheet = workbook.active cell = sheet['A1'] |
Step 5: Creating and Assigning a Color
Now we will assign a color to the selected cell. It’s important to note that openpyxl requires the color in RGB format. We’ll be highlighting our cell in yellow.
1 2 3 |
from openpyxl.styles import PatternFill yellowFill = PatternFill(start_color='FFFF00',end_color='FFFF00',fill_type='solid') cell.fill = yellowFill |
Step 6: Saving the Workbook
We are almost done. All we need to do now is save our changes to the workbook.
1 |
workbook.save('file.xlsx') |
Now, when you open your workbook, the cell A1 of the active sheet should be highlighted in yellow.
Full Python Code
1 2 3 4 5 6 7 8 9 10 11 |
import openpyxl from openpyxl.styles import PatternFill workbook = openpyxl.load_workbook('file.xlsx') sheet = workbook.active cell = sheet['A1'] yellowFill = PatternFill(start_color='FFFF00', end_color='FFFF00', fill_type='solid') cell.fill = yellowFill workbook.save('file.xlsx') |
Output
Conclusion
In this tutorial, you’ve learned how to use Python to interact with Excel workbooks and specifically, how to highlight cells. The power of openpyxl doesn’t stop there, however. This library supports a lot of other Excel features, like formulas, number formatting, pivots, etc.
All this can easily be done from within Python. Learning to automate Excel with Python opens up a wide range of possibilities for data processing and management.