Search code examples
pythonpowerpointpython-pptx

How to add a Hyperlink to a text in table cell on pptx python?


I'm creating a report in pptx-python. I'm trying to add a hyperlink to one of the table cells. Do someone know how I can do it? this is my code :

prs = Presentation()
prs.slide_width = Inches(16)
prs.slide_height = Inches(9)

title_only_slide_layout = prs.slide_layouts[6]
slide = prs.slides.add_slide(title_only_slide_layout)
shapes = slide.shapes

rows = 2
cols = 1
left = Inches(0.5)
top = Inches(1.5)
width = Inches(15)
height = Inches(0.8)
table = shapes.add_table(rows, cols, left, top, width, height).table

table.cell(0,0).text = 'title'
table.cell(1,0).text = 'link'

I want the link text to be a hyperlink. I will appreciate some help :)


Solution

  • Adding hyperlinks is a bit tricky. You'll first need to add a "run" to the text, add the text to be shown, then add the hyperlink address. Eg:

    cell = table.cell(0,1)
    cell_link = cell.text_frame.paragraphs[0].add_run()
    cell_link.text = "Text to display"
    hlink = cell_link.hyperlink
    hlink.address = "https://www.somwehere.com"