Skip to content

How to add a hyperlink to a table. [This is the answer!] #1041

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
NeilRiver opened this issue Jan 12, 2022 · 4 comments
Open

How to add a hyperlink to a table. [This is the answer!] #1041

NeilRiver opened this issue Jan 12, 2022 · 4 comments
Labels
hyperlink Read and write hyperlinks in paragraph

Comments

@NeilRiver
Copy link

NeilRiver commented Jan 12, 2022

Сала малейкум братья мои, я часов 5 еб**** чтобы найти как так сделать, это решение для вас, чтобы оно отображалось в гугле

Sala maleikum my brothers, I fu**** 5 hours to find how to do this, this is a solution for you so that it is displayed in Google

Dear developers, please contact the clinic for the foreskin to be returned to you and you finally made a normal addition to the table

def add_hyperlink(paragraph, url, text, color):

    # This gets access to the document.xml.rels file and gets a new relation id value
    part = paragraph.part
    r_id = part.relate_to(url, docx.opc.constants.RELATIONSHIP_TYPE.HYPERLINK, is_external=True)

    # Create the w:hyperlink tag and add needed values
    hyperlink = docx.oxml.shared.OxmlElement('w:hyperlink')
    hyperlink.set(docx.oxml.shared.qn('r:id'), r_id, )

    # Create a w:r element
    new_run = docx.oxml.shared.OxmlElement('w:r')
    rPr = docx.oxml.shared.OxmlElement('w:rPr')

    # Join all the xml elements together add add the required text to the w:r element
    new_run.append(rPr)
    new_run.text = text
    hyperlink.append(new_run)

    # Create a new Run object and add the hyperlink into it
    r = paragraph.add_run ()
    r._r.append (hyperlink)

    # A workaround for the lack of a hyperlink style (doesn't go purple after using the link)
    # Delete this if using a template that has the hyperlink style in it
    r.font.color.theme_color = MSO_THEME_COLOR_INDEX.HYPERLINK
    r.font.underline = True

    # 0,122,194

    # # Join all the xml elements together add add the required text to the w:r element
    # new_run.append(rPr)
    # new_run.text = text
    # hyperlink.append(new_run)

    # paragraph._p.append(hyperlink)

    return hyperlink
document = Document()
table = document.add_table(rows=1, cols=4, style='Table Grid')
    hdr_cells = table.rows[0].cells
    hdr_cells[0].text = '1'
    hdr_cells[1].text = '2'
    hdr_cells[2].text = '3'
    hdr_cells[3].text = '4'

    for jira, summary, priority, status in table_object[i]:
        row_cells = table.add_row().cells

        p_table = row_cells[0].add_paragraph()
        hyperlink = add_hyperlink(p_table, f'https://jira.sex.com/browse/{jira}', jira, '#0000FF')
        row_cells[1].text = summary
        row_cells[2].text = priority
        row_cells[3].text = status

        row_cells[0].paragraphs[0].paragraph_format.alignment = WD_TABLE_ALIGNMENT.CENTER
        row_cells[2].paragraphs[0].paragraph_format.alignment = WD_TABLE_ALIGNMENT.CENTER

        row_cells[1].paragraphs[0].paragraph_format.alignment = WD_ALIGN_PARAGRAPH.JUSTIFY
        row_cells[3].paragraphs[0].paragraph_format.alignment = WD_ALIGN_PARAGRAPH.JUSTIFY

result

image

@NeilRiver
Copy link
Author

NeilRiver commented Jan 26, 2022

if you wanna without spaces in first table

        paragraph = row_cells[0].paragraphs[0]
        add_hyperlink(paragraph, 'Link url', jira)

@abubelinha
Copy link

abubelinha commented Mar 25, 2023

Thanks. I tried the above code but it didn't work for me:

  • Wrongly indented code after this line?
    table = document.add_table(rows=1, cols=4, style='Table Grid')
    So I removed first indentation level in all lines below that one.
    But I guess there is some missing code where i and table_object should be defined,
    because I got a new error:
  • for jira, summary, priority, status in table_object[i]:
    NameError: name 'table_object' is not defined

@sixlycos
Copy link

sixlycos commented Apr 7, 2023

@abubelinha hello there, I find this issue and use this way solved my problem.
keypoint is use
p_table = row_cells[0].add_paragraph()
to add the cell which u want to add hyperlink.

NeilRiver show the way but did not paste the complete code, you can check my code to solve your problem

def add_hyperlink(paragraph, url, text, color, underline):
    # This gets access to the document.xml.rels file and gets a new relation id value
    part = paragraph.part
    r_id = part.relate_to(url, docx.opc.constants.RELATIONSHIP_TYPE.HYPERLINK, is_external=True)
    # Create the w:hyperlink tag and add needed values
    hyperlink = docx.oxml.shared.OxmlElement('w:hyperlink')
    hyperlink.set(docx.oxml.shared.qn('r:id'), r_id, )
    # Create a w:r element
    new_run = docx.oxml.shared.OxmlElement('w:r')
    # Create a new w:rPr element
    rPr = docx.oxml.shared.OxmlElement('w:rPr')
    # Add color if it is given
    if not color is None:
        c = docx.oxml.shared.OxmlElement('w:color')
        c.set(docx.oxml.shared.qn('w:val'), color)
        rPr.append(c)
    # Remove underlining if it is requested
    if not underline:
        u = docx.oxml.shared.OxmlElement('w:u')
        u.set(docx.oxml.shared.qn('w:val'), 'none')
        rPr.append(u)
    # Join all the xml elements together  add the required text to the w:r element
    new_run.append(rPr)
    new_run.text = text
    hyperlink.append(new_run)
    paragraph._p.append(hyperlink)
    return hyperlink

Word = Document()

test_url = 'https://github.com'

records = (
    (3, '101', 'Spam'),
    (7, '422', 'Eggs'),
    (4, '631', 'Spam, spam, eggs, and spam')
)

table = Word.add_table(rows=1, cols=3)
hdr_cells = table.rows[0].cells
hdr_cells[0].text = 'Qty'
hdr_cells[1].text = 'Id'
hdr_cells[2].text = 'Desc'
for qty, id, desc in records:
    row_cells = table.add_row().cells
    row_cells[0].text = str(qty)
    row_cells[1].text = id
    p_tag = row_cells[2].add_paragraph()
    hyperlink = add_hyperlink(p_tag, test_url, desc, '0000FF', False)

Word.save('table_test_67.docx')

@abubelinha
Copy link

abubelinha commented Apr 23, 2023

Thanks @sixlycos , it worked except for the underlining option:
My links were never underlined, no matters if I pass underline=True or underline=False

So I changed the if not underline code like this:

	if underline:
		u = docx.oxml.shared.OxmlElement('w:u')
		u.set(docx.oxml.shared.qn('w:val'), 'single')
		rPr.append(u)
	else:
		u = docx.oxml.shared.OxmlElement('w:u')
		u.set(docx.oxml.shared.qn('w:val'), 'none')
		rPr.append(u)

More underlining style options are available in #19 and in this documentation
(you need to use them changing 1st letter to lowercase: 'wave', 'double', 'dottedHeavy', and so on).

@abubelinha

@scanny scanny added the hyperlink Read and write hyperlinks in paragraph label Sep 28, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
hyperlink Read and write hyperlinks in paragraph
Projects
None yet
Development

No branches or pull requests

4 participants