MergedCell does not have attribute 'value'

Issue #1191 resolved
Cosmin Polifronie created an issue

Hello. I am using openpyxl to parse an Excel document that uses lots of merged cells. In 2.6, the following piece of code doesn't work anymore:

for col in source.iter_cols(current_col, current_col, row, row + 3):
    values = []
    for item in col:
        values.append(item.value)

The append method works fine for normal cells, but when item is of type MergedCell then the value attribute is not available anymore.

This issue has been introduced in 2.6 (2.5.14 works fine). Does it have anything to do with this change in 2.6? Implement robust for merged cells so that these can be formatted the way Excel does without confusion. Thanks to Magnus Schieder.

Is it intentional? If yes, how should I retrieve the cell's value?

Comments (11)

  1. CharlieC

    MergedCells deliberately don't have a value because they shouldn't really exist. Excel creates them solely for use when adding borders to ranges of merged cells. You can use getattr(item, 'value', None) for checking though I suspect I'll copy the property from Cell for orthogonality.

  2. Cosmin Polifronie reporter

    The second idea sounds like a good plan. Everything that iter_cols returns should have a value, or the value should be accessed the same way for both objects (you could make a method to retrieve the value of a cell object, maybe?).

  3. mario mario

    Hmmm, I don`t really need those merged cells, they just happen to be in the spreadsheet. Any quick solution how to convert the generator to a list? Anything can be put to these "unmerged" cells as long as the structure's fine.

  4. girish lc

    Hi,

    How to use this? Should I check before reading each cell whether it is merged or not ? or is there any other way to do it ?

    It would be really helpful with sample code.

    This is my code: for i in range(1, max_row + 1): for j in range(1, max_col + 1): cell_obj = sheet_obj.cell(i, j) print (cell_obj.value, end = ' ') print (end = '\n')

    This is the error I'm getting from the cell where in encounters the merged cell, AttributeError: 'MergedCell' object has no attribute 'value'

  5. Cosmin Polifronie reporter

    It has been fixed and your code is fine. The fix hasn't been released yet, you'll have to install the library from the git repository. It will probably come in 2.6.1 or 2.7.

  6. girish lc

    Great, thank you,

    Here is my workaround for this which ignores the cell which doesn't have the value, please check and let me know your comment.

    I'm using hasattr function to check this,

    Code: for i in range(1, max_row + 1): for j in range(1, max_col + 1): cell_obj = sheet_obj.cell(i, j) if ((hasattr(cell_obj, "value")) == False): continue print (cell_obj.value, end = ' ') print (end = '\n')

  7. Log in to comment