2017-12-06 34 views
1

파이썬 용 docx 모듈을 사용하는 MS 워드 문서에 하이퍼 링크를 추가하려고합니다.python-docx를 사용하여 MSWord에 하이퍼 링크 추가하기

나는 어디에서나 검색했지만 (공식 문서, StackOverflow, Google) 아무 것도 발견하지 못했습니다.

from docx import Document 

document = Document() 

p = document.add_paragraph('A plain paragraph having some ') 
p.add_hyperlink('Link to my site', target="http://supersitedelamortquitue.fr") 

누구나 그 작업을 수행하는 방법에 대한 아이디어를 가지고 :

내가 좋아하는 뭔가를 원하십니까?

+1

가능합니다. https://github.com/python-openxml/python-docx/issues/384 마지막 답변을 참조하십시오. – planet260

+0

감사합니다. 어떻게 내가 github를 점검하는 것을 잊었 느냐, 나를 바보 취급해라! –

답변

2

예 할 수 있습니다. Reference

import docx 
from docx.enum.dml import MSO_THEME_COLOR_INDEX 

def add_hyperlink(paragraph, text, url): 
    # 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 and a new w:rPr 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 

    return hyperlink 


document = docx.Document() 
p = document.add_paragraph('A plain paragraph having some ') 
add_hyperlink(p, 'Link to my site', "http://supersitedelamortquitue.fr") 
document.save('demo_hyperlink.docx') 
+1

나는 하이퍼 링크와 유사한 스타일을 추가하는 대답을 개선했다. –