Skip to content

Commit e9ea2da

Browse files
committed
Merge pull request #67 from jmcnamara/merged_cells
Read xlsx merged cell elements.
2 parents ff81a3f + d3eddb7 commit e9ea2da

File tree

3 files changed

+36
-0
lines changed

3 files changed

+36
-0
lines changed

tests/merged_cells.xlsx

9.06 KB
Binary file not shown.

tests/test_cell.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,3 +39,26 @@ def test_merged_cells(self):
3939
row_lo, row_hi, col_lo, col_hi = sheet3.merged_cells[0]
4040
self.assertEqual(sheet3.cell(row_lo, col_lo).value, 'MERGED')
4141
self.assertEqual((row_lo, row_hi, col_lo, col_hi), (3, 7, 2, 5))
42+
43+
def test_merged_cells_xlsx(self):
44+
book = xlrd.open_workbook(from_this_dir('merged_cells.xlsx'))
45+
46+
sheet1 = book.sheet_by_name('Sheet1')
47+
expected = []
48+
got = sheet1.merged_cells
49+
self.assertEqual(expected, got)
50+
51+
sheet2 = book.sheet_by_name('Sheet2')
52+
expected = [(0, 1, 0, 2)]
53+
got = sheet2.merged_cells
54+
self.assertEqual(expected, got)
55+
56+
sheet3 = book.sheet_by_name('Sheet3')
57+
expected = [(0, 1, 0, 2), (0, 1, 2, 4), (1, 4, 0, 2), (1, 9, 2, 4)]
58+
got = sheet3.merged_cells
59+
self.assertEqual(expected, got)
60+
61+
sheet4 = book.sheet_by_name('Sheet4')
62+
expected = [(0, 1, 0, 2), (2, 20, 0, 1), (1, 6, 2, 5)]
63+
got = sheet4.merged_cells
64+
self.assertEqual(expected, got)

xlrd/xlsx.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -511,6 +511,7 @@ def __init__(self, sheet, logfile=DLF, verbosity=0):
511511
self.rowx = -1 # We may need to count them.
512512
self.bk = sheet.book
513513
self.sst = self.bk._sharedstrings
514+
self.merged_cells = sheet.merged_cells
514515
self.warned_no_cell_name = 0
515516
self.warned_no_row_num = 0
516517
if ET_has_iterparse:
@@ -528,6 +529,8 @@ def own_process_stream(self, stream, heading=None):
528529
elem.clear() # destroy all child elements (cells)
529530
elif elem.tag == U_SSML12 + "dimension":
530531
self.do_dimension(elem)
532+
elif elem.tag == U_SSML12 + "mergeCell":
533+
self.do_merge_cell(elem)
531534
self.finish_off()
532535

533536
def do_dimension(self, elem):
@@ -539,6 +542,16 @@ def do_dimension(self, elem):
539542
self.sheet._dimnrows = rowx + 1
540543
self.sheet._dimncols = colx + 1
541544

545+
def do_merge_cell(self, elem):
546+
# The ref attribute should be a cell range like "B1:D5".
547+
ref = elem.get('ref')
548+
if ref:
549+
first_cell_ref, last_cell_ref = ref.split(':')
550+
first_rowx, first_colx = cell_name_to_rowx_colx(first_cell_ref)
551+
last_rowx, last_colx = cell_name_to_rowx_colx(last_cell_ref)
552+
self.merged_cells.append((first_rowx, last_rowx + 1,
553+
first_colx, last_colx + 1))
554+
542555
def do_row(self, row_elem):
543556

544557
def bad_child_tag(child_tag):

0 commit comments

Comments
 (0)