Excel 轉化成JSON
import pandas as pd
import json
import osdef excel_to_json(excel_path, sheet_name=0, orient='records', save_path=None):"""將Excel文件轉換為JSON格式并可選擇保存到文件參數:excel_path: Excel文件路徑sheet_name: 工作表名稱或索引,默認為第一個工作表orient: JSON格式取向('records'、'split'、'index'等),默認為'records'save_path: JSON文件保存路徑,如果為None則不保存文件返回:JSON字符串"""df = pd.read_excel(excel_path, sheet_name=sheet_name)df = df.where(df.notnull(), None)json_str = df.to_json(orient=orient, force_ascii=False, indent=2)if save_path:os.makedirs(os.path.dirname(save_path), exist_ok=True)with open(save_path, 'w', encoding='utf-8') as f:f.write(json_str)print(f"JSON文件已保存至: {save_path}")return json_str
if __name__ == "__main__":json_output = excel_to_json(excel_path="data.xlsx",sheet_name="Sheet1",orient='records',save_path="output/data.json" )print("JSON內容預覽:")print(json_output[:200] + "..." if len(json_output) > 200 else json_output)