(My ultimate purpose is to append clickable cells to existing XLSX
.)
I use the code below to extract the cell's display value and the hyperlink.
from openpyxl import load_workbook
xlsFile='hello.xlsx'
wbook = load_workbook(xlsFile)
wsheet1= wbook.get_sheet_by_name('mysheet')
cell1 = wsheet1.cell('A1')
print cell1.value
print cell1.hyperlink
print wsheet1['A1'].value
print wsheet1['A1'].hyperlink
But it returns the following things:
URL1
None
URL1
None
Why the hyperlink
always None
? I did add hyperlink manually for cell A1 and the hyperlink works in Excel 2013.
Unfortunately, it's a bug.
It's a bug in 2012...
Some related thread:
Extracting Hyperlinks From Excel (.xlsx) with Python
Some details of my experiment with hyperlink. I am using
OpenPyXL 2.3.3
.But I cannot load the XLSX file and read the hyperlink just as my question said.
And If I just load and re-save the XLSX file, ALL existing hyperlinks will be lost. Yeah!
A workaround!
Use the formula with OpenPyXL.
My purpose is to
append clickable cells to existing XLSX file
. Sincehyperlink
doesn't work. I use the formula=HYPERLINK(url, displayText)
instead. And luckily, the formula is not lost like previous experiment 3.Other (failed) options I tried:
I looked into the XlsxWriter. But it explicitly says it cannot modify existing XLSX file. So it cannot be used for appending.
I also looked into the
xlrd/xlwt/xlutils
, unfortunately, if you want to edit an existing excel, you have to use xlrd to load it as a read-only workbook, and then use xlutils to convert(copy) it into a writable workbook. And BANG! during the copy, something will be lost which includes theHYPERLINK
formula. According to its doc string, this is a known limitation:And also, xlwt doesn't support XLSX, only supports XLS. That's another reason I decided not to use it.