Openpyxl - Adding hyperlinks to cells in Excel with Python

Learn to add hyperlinks to cells in Excel using Openpyxl module in Python 3.

Openpyxl - Adding hyperlinks to cells in Excel with Python

Prerequisites

  1. Reading Excel data with Openpyxl
  2. Writing to Excel with Openpyxl

There are multiple ways to add a hyperlink to a certain cell in Excel with Python.

Method 1 - Excel built-in function

You can directly use the HYPERLINK built-in function in Excel.

ws.cell(row=1, column=1).value = '=HYPERLINK("{}", "{}")'.format(link, "Link Name")

link - The url link to point
Link Name - The string to display

Code

from openpyxl import Workbook

wb = Workbook()
sheet = wb.active

# Add a hyperlink
sheet.cell(row=1, column=1).value = '=HYPERLINK("{}", "{}")'.format("https://www.google.com", "Check Google")

wb.save("hyperlink_example.xlsx")

Output

Code

from openpyxl import Workbook

wb = Workbook()
sheet = wb.active

# Add a hyperlink
sheet.cell(row=1, column=1).value = '=HYPERLINK("{}", "{}")'.format("https://www.google.com", "Check Google")

sheet.cell(row=2, column=1).hyperlink = "https://www.youtube.com/pylenin"
sheet.cell(row=2, column=1).value = "Pylenin Youtube Channel"
sheet.cell(row=2, column=1).style = "Hyperlink"

wb.save("hyperlink_example.xlsx")

Output

You can see the difference between the 1st and 2nd Method. Setting the style attribute to Hyperlink has styled the cell in a way that it appears like a link.

Method 3 - Hyperlinking to a different Excel sheet in same Workbook

Assuming you have an Excel file named hyperlink_example.xlsx with two sheets named Sheet1 and Sheet2. You want to create an internal link from cell(A1) of Sheet1 to another cell(A1) of Sheet2 using Openpyxl.

Excel uses the # for same file links. You can use it to hyperlink to any cell of any sheet,

Code

from openpyxl import load_workbook

file_name = "hyperlink_example.xlsx"
wb = load_workbook(file_name) 
ws1 = wb.get_sheet_by_name("Sheet1")

# Create hyperlink to relevant cell
link = file_name+"#Sheet2!A1"

ws1.cell(row=1, column=1).hyperlink = link
ws1.cell(row=1, column=1).value = "Refer to Sheet 2 - Cell A1"
ws1.cell(row=1, column=1).style = "Hyperlink"

wb.save(file_name)

Output

Subscribe to Pylenin

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
jamie@example.com
Subscribe