Commit b22fc523 authored by eirikur@Eirikurs-MacBook-Pro.local's avatar eirikur@Eirikurs-MacBook-Pro.local
Browse files

Fix error when loading workbooks containing links that reference merged cells

 - In `bind_hyperlinks`, check if `ref` points to a MergedCell.
   If so, place link on the top-left cell of the merged range.
 - Extend `test_merged_hyperlinks` by adding a hyperlink pointing to a merged
   cell in `complex-styles-worksheet.xml`, then asserting that the link is
   placed on the top-left cell.

--HG--
branch : fix-mergedcell-hyperlink-read-only
parent 22f256f388e6
......@@ -314,16 +314,20 @@ class MergedCell(StyleableObject):
comment = None
hyperlink = None
def __init__(self, worksheet, row=None, column=None):
super(MergedCell, self).__init__(worksheet)
self.row = row
self.column = column
def __repr__(self):
return "<MergedCell {0!r}.{1}>".format(self.parent.title, self.coordinate)
def get_first_cell_in_merged_range(self):
for cell_range in self.parent.merged_cells.ranges:
if self.coordinate in cell_range:
return self.parent.cell(cell_range.min_row, cell_range.min_col)
return None
coordinate = Cell.coordinate
_comment = comment
value = _value
......
......@@ -7,7 +7,7 @@ from warnings import warn
from openpyxl.xml.functions import iterparse
# package imports
from openpyxl.cell import Cell
from openpyxl.cell import Cell, MergedCell
from openpyxl.cell.text import Text
from openpyxl.worksheet.dimensions import (
ColumnDimension,
......@@ -377,7 +377,11 @@ class WorksheetReader(object):
except AttributeError:
pass
else:
self.ws[link.ref].hyperlink = link
cell = self.ws[link.ref]
if isinstance(cell, MergedCell):
cell = cell.get_first_cell_in_merged_range()
if cell is not None:
cell.hyperlink = link
def bind_col_dimensions(self):
......
......@@ -413,6 +413,7 @@
<hyperlink ref="B4:B7" location="'STP nn000TL-10, PKG 2.52'!A1" display="STP 10000TL-10"/>
<hyperlink display="http://test.com" r:id="rId1" ref="A1"/>
<hyperlink ref="A18:B18" display="http://test.com"/>
<hyperlink ref="H24" tooltip="openpyxl" location="https://openpyxl.readthedocs.io/en/stable/"/>
</hyperlinks>
<pageMargins left="0.75" right="0.75" top="1" bottom="1" header="0.5" footer="0.5"/>
<pageSetup orientation="portrait" horizontalDpi="4294967292" verticalDpi="4294967292"/>
......
......@@ -847,6 +847,11 @@ class TestWorksheetReader:
assert ws['A18'].hyperlink.display == 'http://test.com'
assert ws['B18'].hyperlink is None
# Link referencing H24 should be placed on G23 because H24 is a merged cell
# and G23 is the top-left cell in the merged range
assert ws["G23"].hyperlink.tooltip == "openpyxl"
assert ws["H24"].hyperlink is None
def test_tables(self, PrimedWorksheetReader):
reader = PrimedWorksheetReader
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment