pandas版xml json excel互转

import json
import xmltodict
import pandas as pd

# 定义xml转json的函数

class Json_xml():
    def __init__(self):
        pass
    
    # xml转json

    def xmltojson(self,xmlfile,jsonfile):
        xmlstr=''
        with open(xmlfile, 'r', encoding='utf-8') as f:

            xmlstr = f.read()
        # parse是的xml解析器
        xmlparse = xmltodict.parse(xmlstr)
        # json库dumps()是将dict转化成json格式,loads()是将json转化成dict格式。
        # dumps()方法的ident=1,格式化json
        jsonstr = json.dumps(xmlparse, indent=1)
        with open(jsonfile,"w",encoding="utf-8") as f:
            f.write(jsonstr)





    #json转xml函数
    def jsontoxml(self,jsonfile,xmlfile):
        data=''
        with open(jsonfile,'r',encoding="utf-8") as f:
            data=json.load(f)
        xmlstr = xmltodict.unparse(data)
        with open(xmlfile,"w",encoding="utf-8") as f:
            f.write(xmlstr)
    # josn转excel


    # json 转excel
    def json_to_excel(self,jsonfile,excelfile):
        data=pd.read_json(jsonfile)
        data.to_excel(excelfile)
    
    # excel转json
    # 
    def excel_to_json(self,excelfile,jsonfile):
        data=pd.read_excel(excelfile)
        data.to_json(jsonfile)
    
    
    # excel转xml
    def excel_to_xml(self,excelfile,xmlfile):
        self.excel_to_json(excelfile,"text.json")
        self.jsontoxml("text.json",xmlfile)
    
    
    # xml转excel
    
    def xml_to_excel(self,xmlfile,excelfile):
        self.xmltojson(xmlfile,"text.json")
        self.json_to_excel("text.json",excelfile)



if __name__ == "__main__":
    pass

你可能感兴趣的:(pandas版xml json excel互转)