Python を使用して Excel ファイルを JSON ファイルに変換するには:
import pandas as pd
# Load Excel to DataFrame
path_excel = 'path_to_excel_file.xlsx'
df = pd.read_excel(path_excel, engine='openpyxl')
# Convert DataFrame to JSON
json_data = df.to_json(orient='records', indent=4)
print(json_data)
# Write JSON data to file
path_json = 'final_result.json'
with open(path_json, 'w') as json_file:
json_file.write(json_data)
必要に応じて、pip install openpyxl を使用して openpyxl パッケージをインストールします。
Excel を JSON に変換する例
次のデータが store_data という Excel ファイルに保存されているとします。
product_name | price | store_number | store_city | opening_hours | opening_days |
computer | 1200 | 77 | London | 8-18 | Mon-Fri |
printer | 200 | 77 | London | 8-18 | Mon-Fri |
Excel を JSON に変換する Python スクリプトは次のとおりです。
import pandas as pd
# Load Excel to DataFrame
path_excel = 'store_data.xlsx'
df = pd.read_excel(path_excel, engine='openpyxl')
# Convert DataFrame to JSON
json_data = df.to_json(orient='records', indent=4)
print(json_data)
# Write JSON data to a file
path_json = 'final_result.json'
with open(path_json, 'w') as json_file:
json_file.write(json_data)
結果:
[ { “product_name”:”computer”, “price”:1200, “store_number”:77, “store_city”:”London”, “opening_hours”:”8-18″, “opening_days”:”Mon-Fri” }, { “product_name”:”printer”, “price”:200, “store_number”:77, “store_city”:”London”, “opening_hours”:”8-18″, “opening_days”:”Mon-Fri” } ] |