Skip to content

Fix in `Cell.hyperlink`: set (or reset) the cell hyperlink when affected `None` value (#697).

Bitbucket Importer requested to merge bitbucket/merged-pr-139 into branch/2.4

Created originally on Bitbucket by Tantale (Laurent LAPORTE)

Was already merged in Bitbucket before import, marked as merged by the import user

Here is a new PR based on the 2.4 branch (instead of default), to ensure .hgtags file is not modified.

My changes:

  • Fix the issue #697 (see below).
  • Fix minor bugs in unit tests.
  • Add more unit tests.

When we set None to a cell.hyperlink, it creates an Hyperlink with a None target instead of setting None.

The following unit test fails:

def test_hyperlink_none(dummy_cell):
    cell = dummy_cell
    assert cell.hyperlink is None  # OK
    cell.hyperlink = None
    assert cell.hyperlink is None  # FAIL

The workaround:

cell._hyperlink = None

The fix in openpyxl.cell.cell.Cell.hyperlink setter:

@hyperlink.setter
def hyperlink(self, val):
    """Set value and display for hyperlinks in a cell.
    Automatically sets the `value` of the cell with link text,
    but you can modify it afterwards by setting the `value`
    property, and the hyperlink will remain.
    Hyperlink is removed if set to ``None``."""
    if val is None:
        self._hyperlink = None
    else:
        if not isinstance(val, Hyperlink):
            val = Hyperlink(ref="", target=val)
        val.ref = self.coordinate
        self._hyperlink = val
        if self._value is None:
            self.value = val.target or val.location

Merge request reports