如何写超链接到本地​​图片到openpyxl中的单元格?

我使用Python 2.7.3我需要编写超链接到本地​​图片到openpyxl库的单元格。

当我需要添加超链接到网站我写这样的东西:

从openpyxl导入工作簿

wb = Workbook() dest_filename = r'empty_book.xlsx' ws = wb.worksheets[0] ws.title = 'Name' hyperlink to local picture ws.cell('B1').hyperlink = ('http://pythonhosted.org/openpyxl/api.html') hyperlink to local picture ws.cell('B2').hyperlink = ('1.png') # It doesn't work! wb.save(filename = dest_filename) 

我有3个问题:

  1. 我们如何编写超链接,如VBA的风格的function: ActiveCell.FormulaR1C1 = _ "=HYPERLINK(""http://stackoverflow.com/questions/ask"",""site"")"与hyherlink和她的名字
  2. 我们如何写超链接到本地​​图像? ws.cell('B2').hyperlink = ('1.png') # It doesn't work! And I don't now what to do ) Plese, help me )
  3. 我们可以使用unicode超链接来形象吗? 例如当我使用ws.cell('B1').hyperlink = (u'http://pythonhosted.org/openpyxl/api.html') It fail with error! for example we have picture 'russian_language_name.png' and we create hyperlink in exel without any problem. We click to the cell, and then print '=Hyperlink("http://stackoverflow.com/questions/ask";"site_by_russian_language") ws.cell('B1').hyperlink = (u'http://pythonhosted.org/openpyxl/api.html') It fail with error! for example we have picture 'russian_language_name.png' and we create hyperlink in exel without any problem. We click to the cell, and then print '=Hyperlink("http://stackoverflow.com/questions/ask";"site_by_russian_language")

保存文件,解压缩他。 然后我们去他的目录到xl-> worksheets-> sheet1.xml,我们看到标题

<?xml version="1.0" encoding="UTF-8" standalone="true"?>

接着 …

row r="2" x14ac:dyDescent="0.25" spans="2:6">-<cr="B2" t="str" s="1"><f>HYPERLINK("http://stackoverflow.com/questions/ask","site_by_russian_language")</f><v>site_by_russian_language</v></c>

一切OK =)Exel支持Unicode,但是Python的库openpyxl呢? 它支持超链接的Unicode?

由于.xlsx文件中的文件是使用UTF-8编码的XML文件,Unicode超链接不是问题。

关于问题2,我想,你需要包括文件链接的完整path。 如果您无法访问Excel文件中的文件链接,则禁止这种操作的是Excel的安全策略。

我回答了一个类似的问题。 希望这可以帮助。

那么,我可以到达这一点。 虽然没有直接的方式来build立一个超链接,在你的情况下,我们可以这样做。 我能够使用下面的代码build立到现有文件的超链接。

wb=openpyxl.Workbook() s = wb.get_sheet_by_name('Sheet') s['B4'].value = '=HYPERLINK("C:\\Users\\Manoj.Waghmare\\Desktop\\script.txt", "newfile")' s['B4'].style = 'Hyperlink' wb.save('trial.xlsx')提到style属性为'Hyperlink'是关键。 我拥有的所有其他代码对您来说可能并不重要。 style属性会有一个'Normal'的值奇怪的是即使没有style属性,我们工作的超链接也只是它缺乏风格! 当然。 虽然很奇怪,但我看到了陌生的东西。 希望这可以帮助。