在命令行安装:pip install xlrd openpyxl
然后运行python脚本:
[Python] 纯文本查看 复制代码 import os
import pandas as pd
import json
import tkinter as tk
from tkinter import filedialog, messagebox
def convert_to_json(df):
result = {"list": []}
province_dict = {}
for index, row in df.iterrows():
province_code = row["省市代码"]
province = row["省市"]
city_code = row["市代码"]
city = row["市"]
district_code = row["区县市代码"]
district = row["区县"]
if province_code not in province_dict:
province_dict[province_code] = {
"value": province_code,
"label": province,
"children": []
}
city_dict = None
for c in province_dict[province_code]["children"]:
if c["value"] == city_code:
city_dict = c
break
if city_dict is None:
city_dict = {
"value": city_code,
"label": city,
"children": []
}
province_dict[province_code]["children"].append(city_dict)
city_dict["children"].append({
"value": district_code,
"label": district
})
result["list"] = list(province_dict.values())
return result
def load_file():
file_path = filedialog.askopenfilename(filetypes=[("Excel files", "*.xlsx;*.xls")])
if file_path:
# 使用 openpyxl 引擎读取 xlsx 文件,使用 xlrd 引擎读取 xls 文件
if file_path.endswith(".xlsx"):
df = pd.read_excel(file_path, engine='openpyxl')
else:
df = pd.read_excel(file_path, engine='xlrd')
json_data = convert_to_json(df)
result_file_path = os.path.abspath('result.json')
with open(result_file_path, "w", encoding="utf-8") as f:
json.dump(json_data, f, ensure_ascii=False, indent=4)
messagebox.showinfo("完成", f"JSON文件已生成,路径为:\n{result_file_path}")
print(f"JSON文件已生成,路径为:{result_file_path}")
# 创建Tkinter主窗口
root = tk.Tk()
root.withdraw() # 隐藏主窗口
# 显示文件选择对话框
load_file()
|