excel2json.py 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. import pandas as pd
  2. import json
  3. import os
  4. import glob
  5. import shutil
  6. # 定义一个函数来将Excel文件中的部分数据转换为JSON
  7. def excel2json(df, json_file_path):
  8. # 将DataFrame的选定部分转换为JSON格式
  9. print(f"json_file_path: {json_file_path}")
  10. # print(f"json_file_path.columns: {df.columns}")
  11. # print(f"json_file_path.columns.values: {df.columns.values}")
  12. # print(f"json_file_path.index: {df.index}")
  13. # print(f"json_file_path.index.values: {df.index.values}")
  14. # print(f"json_file_path.values: {df.values}")
  15. df.fillna(0, inplace=True)
  16. keys = df.columns.values
  17. key_len = len(keys)
  18. types = df.iloc[0].values
  19. values = df.iloc[2:].values
  20. json_data = ""
  21. if types[0] == "string" :
  22. json_data = "{\n"
  23. for line in values :
  24. for i in range(1, key_len):
  25. if not keys[i].startswith("_"):
  26. if types[i] == "string":
  27. if line[i] != 0:
  28. json_data += f' "{line[0]}":"{line[i]}"\n'
  29. break
  30. elif types[i] == "num":
  31. json_data += f' "{line[0]}":{line[i]}\n'
  32. break
  33. json_data += "}"
  34. else :
  35. json_data = "["
  36. for line in values :
  37. line_data = "\n {"
  38. for i in range(key_len):
  39. if not keys[i].startswith("_"):
  40. if types[i] == "string":
  41. if line[i] == 0 :
  42. line_data += f'"{keys[i]}":"", '
  43. else:
  44. line_data += f'"{keys[i]}":"{line[i]}", '
  45. elif types[i] == "num":
  46. line_data += f'"{keys[i]}":{(line[i])}, '
  47. line_data = line_data[0:-2]
  48. line_data += "},"
  49. json_data += line_data
  50. json_data = json_data[0:-1]
  51. json_data += "\n]"
  52. # print(f"json_data: {json_data}")
  53. # 写入JSON文件
  54. with open(json_file_path, 'w', encoding='utf-8') as json_file:
  55. json_file.write(json_data)
  56. # 获取当前脚本的文件路径
  57. script_path = os.path.abspath(__file__)
  58. # 获取当前脚本所在的目录
  59. script_dir = os.path.dirname(script_path)
  60. print(f"当前脚本文件路径: {script_path}")
  61. print(f"当前脚本所在目录: {script_dir}")
  62. # 设置Excel和JSON文件的路径
  63. excel_file_path = os.path.join(script_dir, "excel") # 替换为你的Excel文件路径
  64. json_file_path = os.path.join(script_dir + "../../../../assets/hall", "data") # 替换为你想要保存的JSON文件路径
  65. #print(f" 终点:{script_dir + "../../../../assets/AssetPackage"}")
  66. #创建excel目录
  67. if not os.path.exists(excel_file_path) :
  68. os.makedirs(excel_file_path)
  69. #删除旧json目录,并创建新的
  70. if os.path.exists(json_file_path) :
  71. shutil.rmtree(json_file_path)
  72. os.makedirs(json_file_path)
  73. #读出所有excel文件
  74. excel_files = glob.glob(os.path.join(excel_file_path, '*.xlsx'))
  75. for file in excel_files:
  76. print(f"excel file: {file}")
  77. file_name = os.path.basename(file)
  78. if not file_name.startswith("_") :
  79. # 读取Excel文件中的所有sheets
  80. xls = pd.ExcelFile(file)
  81. # 获取所有sheet名
  82. sheet_names = xls.sheet_names
  83. for sheet_name in sheet_names:
  84. if not sheet_name.startswith("_"):
  85. excel_data = pd.read_excel(xls, sheet_name=sheet_name)
  86. excel2json(excel_data, os.path.join(json_file_path, sheet_name + ".json"))
  87. # 关闭Excel文件
  88. xls.close()
  89. print(f"Selected data from Excel file '{excel_file_path}' has been converted to JSON and saved as '{json_file_path}'.")