pandas pd读取xlsx或者csv文件

def get_json_from_xls(xls_path):
    df = pd.read_excel(xls_path)
    arr = df.to_json(orient='records')
    return arr

def get_json_from_csv(xls_path, index_header):
    try:
        df = pd.read_csv(xls_path, header=index_header)
        arr = df.to_json(orient='records')
        sa = json.loads(arr)[0]
        if len(sa.keys()) < 2:
            index_header = index_header + 1
            return get_json_from_csv(xls_path, index_header)
        return arr
    except Exception as e:
        if str(e).__contains__("list index out of range"):
            return "[]"
        index_header = index_header + 1
        return get_json_from_csv(xls_path, index_header)

def get_arr_from_xlsx_or_csv(path, header_index=0):
    if path.__contains__(".xls"):
        return get_json_from_xls(path)
    elif path.__contains__(".csv"):
        return get_json_from_csv(path, header_index)

  

 

 

done

 

posted @ 2025-06-24 15:53  liskov_design  阅读(12)  评论(0)    收藏  举报