【发布时间】:2015-10-27 11:52:40
【问题描述】:
我已使用df.to_excel 将pandas DataFrame 转换为 Excel 工作表。
现在,我想为一列中的值添加超链接。换句话说,当客户看到我的 Excel 表格时,他将能够单击一个单元格并打开一个网页(取决于该单元格中的值)。
【问题讨论】:
标签: python excel pandas hyperlink
我已使用df.to_excel 将pandas DataFrame 转换为 Excel 工作表。
现在,我想为一列中的值添加超链接。换句话说,当客户看到我的 Excel 表格时,他将能够单击一个单元格并打开一个网页(取决于该单元格中的值)。
【问题讨论】:
标签: python excel pandas hyperlink
你可以使用HYPERLINK函数
import pandas as pd
df = pd.DataFrame({'link':['=HYPERLINK("http://www.someurl.com", "some website")']})
df.to_excel('test.xlsx')
【讨论】:
df.to_excel('test.xlsx') 并尝试一下,我只是尝试了一个锚链接,它对我有用
"的链接?谢谢
" 的网址,您需要将" 替换为%7B。可以使用str.replace()。
基于@guillaume-jacquenot 的方法,我们可以使用apply 将其应用于整个系列。
df = pd.DataFrame({'Year': [2000, 2001, 2002 , 2003]})
为了整洁,我写了一个辅助方法。
def make_hyperlink(value):
url = "https://custom.url/{}"
return '=HYPERLINK("%s", "%s")' % (url.format(value), value)
然后,apply 到系列:
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")
【讨论】:
来自@maxymoo 的回答,这是一个完整的例子
import pandas as pd
df = pd.DataFrame({'Year': [2000, 2001, 2002 , 2003]})
df['link'] = '-'
df.set_value(0, 'link', '=HYPERLINK("https://en.wikipedia.org/wiki/2000", 2000)')
df.set_value(1, 'link', '=HYPERLINK("https://en.wikipedia.org/wiki/2001", 2001)')
df.set_value(2, 'link', '=HYPERLINK("https://en.wikipedia.org/wiki/2002", 2002)')
df.set_value(3, 'link', '=HYPERLINK("https://en.wikipedia.org/wiki/2003", 2003)')
df.to_excel('test.xlsx', index = False)
【讨论】:
你可以使用:
df = pd.DataFrame(list(range(5)), columns=['a'])
df['a'] = df['a'].apply(lambda x: '<a href="http://youtube.com/{0}">link</a>'.format(x))
HTML(df.to_html(escape=False))
【讨论】:
to_excel 的其他答案有正确的方法。
from IPython.display import HTML
我正在从 excel 文件生成文本文件,并希望将生成的 .txt 文件的名称链接到 Dataframe 中特定的现有列。
我试图将存储生成的 .txt 文件的本地驱动器目录推送到相应的“文件名”。这样在单击文件名时,它将打开 .txt 文件。
rancheck_DF = pd.read_excel(excel_file, delim_whitespace = True, encoding = 'utf-8')
for index_df in range(len(rancheck_DF)):
Desc = rancheck_DF.loc[index_df,'Description Text']
MainFile = rancheck_DF.loc[index_df,'File Name']
fileName = r'.\Documents\TestF\TestF_{}.txt'.format(index_df)
with open(fileName, 'w', encoding='utf-8') as txtfile:
txtfile.write(Desc)
rancheck_DF.loc[index_df,'File Name'] = '=HYPERLINK("{}","{}")'.format(fileName,MainFile)
rancheck_DF.to_excel('./damn.xlsx', index=None)
【讨论】: