import xdrlib ,sys import xlrd import json reload(sys) sys.setdefaultencoding("utf-8") TYPE_CH = 0 TYPE_EN = 1 TYPE_FR = 2 class LanUnit(): def __init__(self): self.jVal = None self.id = 0 self.fr = '' self.en = '' self.ch = '' def init_unit(self, id, jVal): self.jVal =jVal self.id = id try: self.fr = jVal['fr'] self.en = jVal['en'] self.ch = jVal['ch'] except: pass def is_cur_unit(self, id): return id == self.id def get_FR(self): return self.fr def get_EN(self): return self.en def get_CH(self): return self.ch class LanPool(): def __init__(self): self.lan_dict = {} @classmethod def reload_config(self): self.init_map_from_json() def init_map_from_json(self): ''' self.raw_config = { "1001": { "fr":"fr", "en":"en", "ch":"ch" }, "1002": { "fr": "fr", "en": "en", "ch": "ch" } } ''' self.raw_config = { "1001": { "fr": "fr", "en": "en", "ch": "ch" }, "1002": { "fr": "fr", "en": "en", "ch": "ch" } } for rc in self.raw_config: jVal = self.raw_config[rc] lu = LanUnit() lu.init_unit(rc) self.lan_dict[rc] = lu def has_key(self, id): return hasattr(self.lan_dict, id) def get_str(self, id, type): ID_ERROR = 'ID_ERROR(%d)' TYPE_ERROR = 'TYPE_ERROR(%d)' sRet = '' if self.has_key(id): lan_unit = self.lan_dict[id] if type == TYPE_FR: sRet = lan_unit.get_FR() elif type == TYPE_EN: sRet = lan_unit.get_EN() elif type == TYPE_CH: sRet = lan_unit.get_CH() else: sRet = TYPE_ERROR % type else: sRet = ID_ERROR % id if sRet == '': sRet = 'UNKNOWN ERROR| type->%d | id->%d ', type, id return sRet
class ExcelToJson(): '''''' @classmethod def open_excel(cls, sPath): try: cls.data = xlrd.open_workbook(sPath) except Exception, e: print str(e) @classmethod def data_to_json(cls, sExcel_Path, sOutput_Path, sheet_index): cls.open_excel(sPath) if cls.data == None: return table = cls.data.sheets()[sheet_index] nrows = table.nrows ncols = table.ncols colnames = table.row_values(0) jVal = {} for i in range(1, nrows): id = int(table.cell_value(i, 0)) ch = table.cell_value(i, 1) en = table.cell_value(i, 2) fr = table.cell_value(i, 3) sub_jVal = { 'ch':ch, 'en':en, 'fr':fr } jVal[id] = sub_jVal # Multilingual with open(sOutput_Path, 'w') as json_file: json_file.write(json.dumps(jVal, sort_keys=True, indent=4, ensure_ascii=False))#unicode到文字 if __name__ == "__main__": etj = ExcelToJson() sPath = '123.xlsx' sPath1 = 'Multilingual.json' etj.data_to_json(sPath, sPath1, 0)