Python: Read Excel Merged Cells with openpyxl
In Python, the openpyxl library can be used to read data from Excel files, including data from merged cells.
Firstly, you need to install the openpyxl library. You can use the pip command to install it:
pip install openpyxl
Next, you can use the following code to read the data from merged cells:
from openpyxl import load_workbook
# 加载Excel文件
workbook = load_workbook('filename.xlsx')
# 选择工作表
worksheet = workbook['Sheet1']
# 遍历所有合并单元格
for merged_cell in worksheet.merged_cells.ranges:
# 获取合并单元格的起始行、起始列、结束行、结束列
start_row, start_column, end_row, end_column = merged_cell.bounds
# 获取合并单元格的值
merged_cell_value = worksheet.cell(start_row, start_column).value
# 打印合并单元格的值
print(merged_cell_value)
In the code, first use the load_workbook function to load the Excel file. Then, select the worksheet by specifying the worksheet name. Next, use the merged_cells attribute to get all merged cells, and use the bounds method to get the start row, start column, end row, and end column of the merged cells. Finally, use the cell method to get the value of the merged cells.
Note: If the merged cell spans multiple rows or columns, you can handle it according to your needs.
I hope this helps you!