Detect merged cells in an Excel sheet using openpyxl
In this tutorial, we will see how to detect merged cells in an excel sheet using openpyxl. ‘openpyxl’ is a Python library used to read or write an Excel file with the extension .xlsx/.xlsm/.xltx/.xltm.
First of all, we need to install the openpyxl library:
! pip install openpyxl
Note: Before starting the code, create an Excel file with some data or you can use an existing file.
Example of excel file:
load_workbook() is a function from the openpyxl module which is used when we have to access the MS Excel file.
Now, let’s import the function in our code.
Note: It only works on already created excel files.
from openpyxl import load_workbook
This function takes the excel file path as an argument. So we need to pass the file location to access it.
path = 'F:\Aakanksha\Jupyter\IRIS.xlsx' wb = load_workbook(path)
Now select the active sheet from the workbook. You can select any other sheet on which you want to perform the task by specifying its name.
sheet = wb.active #to select other sheet use sheet = wb['sheet name']
Now to print the merged cells from an excel sheet using the merged_cells function.
ranges return the cell range of merged cells in format<starting_cellno : ending_cellno>
Below is the given output:
[<MergedCellRange E1:F1>, <MergedCellRange A10:B10>, <MergedCellRange C4:D4>, <MergedCellRange A6:B6>]
Leave a Reply