自学内容网 自学内容网

最快捷读取xlsx,用python读取excel转换成json

这是中英文json,用在国际化vue上的,业务人员统计的表格,我需要读取进行转换

# -*- coding: utf-8 -*-

import pandas as pd
import json


# 读取Excel文件中的数据
excel_file = r'D:\解析excel\中英.xlsx'
df = pd.read_excel(excel_file)

# 生成中文JSON和英文JSON
cn_data = {}
en_data = {}
special_data_cn = {}
special_data_en = {}


for index, row in df.iterrows():
    key = str(row.iloc[0])  # 强制将key转换为字符串类型
    value_cn = row.iloc[1]
    value_en = row.iloc[2]

    if "." in key:  # 如果键名中包含 "."
        parent_key, sub_key = key.split(".", 1)  # 分割键名为父键和子键
        if parent_key not in special_data_cn:
            special_data_cn[parent_key] = {}
            # childKey = key.split(".")[1]
        special_data_cn[parent_key][key] = value_cn
    if "." in key:  # 如果键名中包含 "."
        parent_key, sub_key = key.split(".", 1)  # 分割键名为父键和子键
        if parent_key not in special_data_en:
            special_data_en[parent_key] = {}
            # childKey = key.split(".")[1]
        special_data_en[parent_key][key] = value_en


    else:
        cn_data[key] = value_cn
        en_data[key] = value_en

# 将特殊处理的JSON对象写入txt文件
with open('special_data_cn.json', 'w') as special_file:
    json.dump(special_data_cn, special_file, ensure_ascii=False, indent=4)# 将特殊处理的JSON对象写入txt文件
with open('special_data_en.json', 'w') as special_file:
    json.dump(special_data_en, special_file, ensure_ascii=False, indent=4)

# 将中文JSON对象写入txt文件
with open('cn_data.json', 'w') as cn_file:
    json.dump(cn_data, cn_file, ensure_ascii=False, indent=4)

# 将英文JSON对象写入txt文件
with open('en_data.json', 'w') as en_file:
    json.dump(en_data, en_file, ensure_ascii=False, indent=4)

最终结果


原文地址:https://blog.csdn.net/weixin_42759398/article/details/137144190

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!