stone rock
stone rock

Reputation: 1953

How to get the value from merged cells in xlsx file using python?

I am trying to get the value from cell with row = 11 and column B and C. See screenshot for more clarification.

I tried following code using xlrd package but it does not print anything.

import xlrd 

path = "C:/myfilepath/data.xlsx"

workbook = xlrd.open_workbook(path)

sheet = workbook.sheet_by_index(0)

sheet.cell_value(10,1)
sheet.cell_value(10,2)

I am not able to output the value from particular merged cells using xlrd package in python.

Above code should print the cell value i.e PCHGFT001KS

enter image description here

Upvotes: 1

Views: 2232

Answers (1)

SgtMajorJay
SgtMajorJay

Reputation: 129

I don't know how xlrd works, but I do know how the lovely openpyxl works. You should use openpyxl! it's a robust tool for working with xlsx files. (NOT xls).

import openpyxl
wb = openpyxl.load_workbook(excel)
ws = wb[wb.get_sheet_names()[0]]
print(ws['B11'].value)

Extra:

If you want to unmerge those blocks you can do the following.

for items in ws.merged_cell_ranges:
ws.unmerge_cells(str(items))
wb.save(excel)

Upvotes: 2

Related Questions