openpyxlでexcelの結合セルの情報を表示する

openpyxlのインストール

$ sudo pip install openpyxl

https://openpyxl.readthedocs.io/en/stable/index.html


excelファイルを作成してみる

$ python
Python 2.7.5 (default, Aug  4 2017, 00:39:18) 
[GCC 4.8.5 20150623 (Red Hat 4.8.5-16)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from openpyxl import Workbook
>>> wb = Workbook()
>>> 
>>> # grab the active worksheet
... ws = wb.active
>>> 
>>> # Data can be assigned directly to cells
... ws['A1'] = 42
>>> 
>>> # Rows can also be appended
... ws.append([1, 2, 3])
>>> 
>>> # Python types will automatically be converted
... import datetime
>>> ws['A2'] = datetime.datetime.now()
>>> 
>>> # Save the file
... wb.save("sample.xlsx")
>>> 


作成したファイル


A1:A2, B2:C2を連結して保存する

>>> from openpyxl import load_workbook
>>> wb = load_workbook(filename = 'sample.xlsx')
>>> ws = wb.active
>>> ws.merged_cells
<MultiCellRange [A1:A2 B2:C2]>
>>> ws.merged_cells.ranges
[<CellRange A1:A2>, <CellRange B2:C2>]
>>>