import os
import requests as re
import json
from openpyxl import Workbook
from openpyxl.utils import get_column_letter
response = re.get('I cant show the api here but imagine a url')
data = response.json()
api = data
# Save JSON file
directory = 'c:/omri'
filename_json = 'Turge.json'
filepath_json = os.path.join(directory, filename_json)
with open(filepath_json, 'w') as file:
json.dump(api, file)
print(f"The JSON file '{filename_json}' has been saved to '{directory}'.")
# Convert JSON to Excel
filename_xlsx = 'Turge.xlsx'
filepath_xlsx = os.path.join(directory, filename_xlsx)
workbook = Workbook()
sheet = workbook.active
# Write column headers
headers = list(api[0])
for col_num, header in enumerate(headers, 1):
column_letter = get_column_letter(col_num)
sheet[f"{column_letter}1"] = header
# Write data rows
for row_num, row_data in enumerate(api, 2):
for col_num, value in enumerate(row_data.values(), 1):
column_letter = get_column_letter(col_num)
try:
# Attempt to convert the value to string
if isinstance(value, dict):
converted_value = json.dumps(value) # convert dict to JSON string
else:
converted_value = str(value) # convert other values to string
sheet[f"{column_letter}{row_num}"] = converted_value
except Exception as e:
print(f"Error converting value: {value}. Skipping...")
print(f"Error message: {str(e)}")
# Save Excel file
workbook.save(filepath_xlsx)here
嘿!我有一个包含以下详细信息的 api:
{
'_id': 'rieiwrijt5593r94',
'lastvaluerecevivedat': '2023-5-16t08:59',
'status': 'up' ,
'name' : 'eltex',
'description': 'eltex for good',
'isParent':true,
'isexcluded':none,
'isdependancy': false
'parent': [none],
'updatedat': '2023-5-16
(api有很多行,这只是为了举例)
我需要制作一个脚本来将这个 api 中的数据抓取到 JSON 和 Excel 中,但由于某种原因我无法将其转换为 Excel 或 str, 这是我的错误;
ValueError (cannot convert {0!r} to excel .format(value)
value error: cannot convert {
'_id': 'rieiwrijt5593r94',
'lastvaluerecevivedat': '2023-5-16t08:59',
'status': 'up' ,
'name' : 'eltex',
'description': 'eltex for good',
'isParent':true,
'isexcluded':none,
'isdependancy': false
'parent': [none],
'updatedat': '2023-5-16'
} to Excel