有时我们把pandas的DataFrame 写入excel时, 明明字符串是一个网址链接, 但是却不能在excel里直接点击打开, 有时却可以, 具体原因不详, 不过以下两个方法可以解决问题
第一种方法, 写一个函数, 把相应字段做转换
def excel_url_fun( input_value ):
''' 把一个网址字符串转换为excel公式 '''
return f'=HYPERLINK("{input_value}","{input_value}")'
if __name__ == "__main__":
df = pd.DataFrame({'url': ['https://www.baidu.com', 'https://www.163.com', 'https://www.csdn.net']})
df['link'] = '-'
df['link'] = df['url'].apply(lambda x: excel_url_fun(x))
df.to_excel('test.xlsx', index = False)
第二种方法, 使用 options={'strings_to_urls': True} 参数, 保存出来的xlsx文件里面如果有https://xxx的url字符串, 就可以点击打开 , Python3.8.5 亲测通过
with pd.ExcelWriter( "./datapd/focus.xlsx" , engine='xlsxwriter',options={'strings_to_urls': True}) as writer:
df.to_excel(writer, index=False)