【问题标题】:Hyperlink style in OpenpyxlOpenpyxl 中的超链接样式
【发布时间】:2020-11-20 04:02:55
【问题描述】:

在openpyxl中,你可以像这样设置一个超链接:

cell.hyperlink = r'..\somedir\somefile.txt'

但是,这不会应用您在 Excel 中设置超链接时获得的超链接样式。您可以应用带有蓝色文本和下划线的样式,但是当您打开文档时,访问过的超链接不会改变颜色。

有没有办法用 openpyxl 来指定一个超链接样式,就像在 Excel 中设置的超链接一样?

【问题讨论】:

    标签: python openpyxl


    【解决方案1】:

    你必须改变样式属性

    cell.style = "Hyperlink"
    

    【讨论】:

      【解决方案2】:
      import openpyxl
      from openpyxl.styles import Font, Color, colors
      #...
      
      # alternative 1: set hyperlink property to cell
      def link_1(cell, link, display=None):
          cell.hyperlink = link
          cell.font = Font(u='single', color=colors.BLUE)
          if display is not None:
              cell.value = display
      
      # alternative 2: use Excel formula HYPERLINK
      def link_2(cell, link, display='link'):
          cell.value = '=HYPERLINK("%s", "%s")' % (link, display)
          cell.font = Font(u='single', color=colors.BLUE)
      
      # examples
      link_1(ws['B2'], '#sheet3!A1', 'link_text') # internal link
      link_2(ws['B3'], '#sheet3!A1', 'link_text') # internal link
      link_1(ws['B4'], 'https://www.google.com/', 'Google') # web link
      

      【讨论】:

        【解决方案3】:

        我使用了Font,它成功了。

        from openpyxl.styles import Font
        hyperlink = Font(underline='single', color='0563C1')
        # ...
        cell.font = hyperlink
        

        应该有一个名为Hyperlinkbuiltin sytle,但我没有设法让它工作......

        【讨论】:

          【解决方案4】:

          尝试像这样添加超链接样式

          ft = Font()
          ft.underline = 'single'    # add single underline
          ft.color = Color(rgb='000000FF')  # add blue color
          cell.font = ft
          

          【讨论】:

            【解决方案5】:

            这对我有用:

            cell.value = '=HYPERLINK("{}", "{}")'.format('/my/unix/path/data.html', 'theData')
            cell.style='Hyperlink'
            

            其中 'theData' 是人们在单元格中看到的显示值。

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2011-03-24
              • 2012-01-30
              • 1970-01-01
              • 2016-12-28
              • 1970-01-01
              相关资源
              最近更新 更多