我正在尝试为一款名为《Torn City》的游戏制作一份 Excel 工作簿。我希望用户能够将他们的游戏密钥输入到单元格中,然后 Excel 自动从具有组合密钥的链接中提取数据。 例如,这是我的密钥(VNWZibo54fSCUM01),数据链接为:https://api.torn.com/user/?selections=honors&key=VNWZibo54fSCUM01 现在,当您访问这个特定网站时,它会显示您在游戏中获得的奖项,它采用 JSON 格式,其中包含 Honors_awarded 和 Honors_time 两部分。 我希望当用户将其密钥输入单元格时显示 Honors_awarded 列表。
我已经能够通过这个url获取excel中的数据(https://api.torn.com/user/?selections=honors&key=VNWZibo54fSCUM01)
但我想要一个更用户友好的界面。 我希望通过简单地让用户将密钥输入到出现数据的单元格中来完成此操作
可能无关紧要,但我也有这个Python代码,可以获取我想要的数据,但我不知道这是否能够在Excel中
import requests
api = input("Enter your api key")
url = f"https://api.torn.com/user/?selections=honors&key={api}"
response = requests.get(url)
if response.status_code == 200:
data = response.json() # Parse JSON response into a Python dictionary
if 'honors_awarded' in data:
honors_awarded = data['honors_awarded']
for data_list in honors_awarded:
print(data_list)
else:
print("The key 'honors_awarded' does not exist in the response.")
else:
print("Failed to retrieve data:", response.status_code)
有什么建议吗?
使用
pandas
创建了简单的解决方案,尽管不是很方便,因为需要几个步骤:
file.xlsx
代码:
import requests
import pandas as pd
df = pd.read_excel('file.xlsx')
try:
key = df.columns.values[0]
except IndexError:
print('API key not found!')
exit()
response = requests.get(f'https://api.torn.com/user/?selections=honors&key={key}')
if response.status_code == 200:
data = response.json()
if 'honors_awarded' in data:
df = pd.DataFrame({key: data['honors_awarded']})
try:
df.to_excel('file.xlsx', index=False)
except PermissionError:
print('Permission denied! You need to close Excel file!')
else:
print('The key "honors_awarded" does not exist in the response.')
else:
print('Failed to retrieve data:', response.status_code)