import pandas as pd
import json
import csv

def excel_to_csv(excel_path, csv_path):
    """Excel转CSV"""
    try:
        df = pd.read_excel(excel_path)
        df.to_csv(csv_path, index=False, encoding='utf-8-sig')
        return True
    except Exception as e:
        raise Exception(f"Excel转CSV失败: {str(e)}")

def csv_to_excel(csv_path, excel_path):
    """CSV转Excel"""
    try:
        df = pd.read_csv(csv_path)
        df.to_excel(excel_path, index=False)
        return True
    except Exception as e:
        raise Exception(f"CSV转Excel失败: {str(e)}")

def json_to_excel(json_path, excel_path):
    """JSON转Excel"""
    try:
        with open(json_path, 'r', encoding='utf-8') as f:
            data = json.load(f)
        
        # 如果是列表格式的JSON
        if isinstance(data, list):
            df = pd.DataFrame(data)
        else:
            # 如果是字典格式，转换为单行DataFrame
            df = pd.DataFrame([data])
        
        df.to_excel(excel_path, index=False)
        return True
    except Exception as e:
        raise Exception(f"JSON转Excel失败: {str(e)}")

def excel_to_json(excel_path, json_path):
    """Excel转JSON"""
    try:
        df = pd.read_excel(excel_path)
        data = df.to_dict('records')
        
        with open(json_path, 'w', encoding='utf-8') as f:
            json.dump(data, f, ensure_ascii=False, indent=2)
        
        return True
    except Exception as e:
        raise Exception(f"Excel转JSON失败: {str(e)}")

def csv_to_json(csv_path, json_path):
    """CSV转JSON"""
    try:
        df = pd.read_csv(csv_path)
        data = df.to_dict('records')
        
        with open(json_path, 'w', encoding='utf-8') as f:
            json.dump(data, f, ensure_ascii=False, indent=2)
        
        return True
    except Exception as e:
        raise Exception(f"CSV转JSON失败: {str(e)}")

def json_to_csv(json_path, csv_path):
    """JSON转CSV"""
    try:
        with open(json_path, 'r', encoding='utf-8') as f:
            data = json.load(f)
        
        df = pd.DataFrame(data)
        df.to_csv(csv_path, index=False, encoding='utf-8-sig')
        return True
    except Exception as e:
        raise Exception(f"JSON转CSV失败: {str(e)}")