add hyperlink to excel sheet created by pandas dataframe to_excel method

后端 未结 5 1566
栀梦
栀梦 2020-12-15 11:56

I have converted a pandas DataFrame to an Excel sheet using df.to_excel.

Now, I want to add hyperlinks to the values in one column. In other words, when a customer

5条回答
  •  [愿得一人]
    2020-12-15 12:02

    Building on the approach by @guillaume-jacquenot we can use apply to apply this to an entire Series.

    df = pd.DataFrame({'Year': [2000, 2001, 2002 , 2003]})
    

    For cleanliness, I wrote a helper method.

    def make_hyperlink(value):
        url = "https://custom.url/{}"
        return '=HYPERLINK("%s", "%s")' % (url.format(value), value)
    

    Then, apply it to the Series:

    df['hyperlink'] = df['Year'].apply(lambda x: make_hyperlink(x))
    

    >

        Year    hyperlink
    0   2000    =HYPERLINK("https://custom.url/2000", "2000")
    1   2001    =HYPERLINK("https://custom.url/2001", "2001")
    2   2002    =HYPERLINK("https://custom.url/2002", "2002")
    3   2003    =HYPERLINK("https://custom.url/2003", "2003")
    

提交回复
热议问题