Excel 2 Json For Python In Mac

http://www.manew.com/thread-107188-1-1.html

前言:      由于工作的原因,开发环境变成了Mac自己原先有一套在window环境下Excel转Json的工具。想着以后都在Mac下工作了,那就再来个Mac版本的吧!

这是五月份写的一些代码,现在才整理出来!有点晚了!!有不足之处请帮忙指出!大家共同学习!


功能:
   Excel表格数据导出为Json格式数据;支持多Excel文件,多表表单导出。导出文件存放在out文件夹中。
Excel文件格式要求:
            *.xlsx *.xls
      必须保证Excel文件后缀为”.xlsx”或“.xls”;excel文件放在files文件中。
支持格式:
Int: 整型数据
Float: 浮点数据
Boolean: 布尔数据
String:  字符串数据

开发运行环境
       开发语言: Python3.0
       Mac环境: Pycharm
       Windows环境:配置相关开发环境
       引申其它:也可使用cx_freeze(windows&mac都支持)生成独立可执行文件
导出格式:
       文件名_表单名.json

数据文件结构如下图:
Excel 2 Json For Python In Mac 
使用方法:

将所需转换的excel文件放置在files文件中,双击运行ExcelToJson  ;
数据将存储在out文件中
Python3.0代码:
[AppleScript] 纯文本查看 复制代码
?
 
001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034
035
036
037
038
039
040
041
042
043
044
045
046
047
048
049
050
051
052
053
054
055
056
057
058
059
060
061
062
063
064
065
066
067
068
069
070
071
072
073
074
075
076
077
078
079
080
081
082
083
084
085
086
087
088
089
090
091
092
093
094
095
096
097
098
099
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
#!/usr/local/bin/python
# -*- coding: utf-8 -*
#Excel表格转出josn(支持多sheet导出)
#author Flyer
#data 2017.05.24
import xlrd
import json
import codecs
import os
import sys
 
# determine if application is a script file or frozen exe
if getattr(sys, 'frozen', False):
    isEXE = True
    application_path = os.path.dirname(sys.executable)
elif __file__:
    isEXE = False
    application_path = os.path.dirname(__file__)
 
outpath = "/out"
 
def ExcelToJson(file_path):
    print("打开Excel文件:"+file_path)
    if get_data(file_path) is not None:
        book = get_data(file_path)
 
        # 获取sheet页
        worksheets = book.sheet_names()
        #print(str(worksheets))
 
        remove_target = "./#.xlsx#.xls"
        target_list = str.split(remove_target,"#")
 
        file_name = file_path.split('/')[-1]
 
        for target in target_list:
            if file_name.find(target)!=-1:
                file_name = file_name.replace(target,"")
 
 
        for sheet in worksheets:
            #print('%s,%s' % (worksheets.index(sheet), sheet))
            sheet_index = worksheets.index(sheet)
            sheet = book.sheet_by_index(int(sheet_index))
            row_titles = sheet.row(2)  # 表单标题集
            row_types = sheet.row(1) #数据类型
            nrows = sheet.nrows  # 行号集
            ncols = sheet.ncols  # 列号集
 
            result_file_name = str(file_name + "_" + worksheets[int(sheet_index)])
 
            #print("resulat_file_name:"+result_file_name)
 
            if IsHaveRepeatFiel(row_titles):
                print("表格:"+file_path+"&表格页:"+sheet.name+" 有重复字段!!!!!!")
                return
 
            result = {}  # 定义json对象
            result[result_file_name] = [] #设置数组名
            # 遍历所有行,将excel转化为json对象
            for i in range(nrows):
                if i == 0 or i == 1 or i == 2: #说明文字 && 属性字段 &&数据类型 排除
                    continue
                temp = {}
                # 遍历当前行所有列
                for j in range(ncols):
                    # 获取当前列中文标题
                    title_de = str(row_titles[j])
 
                    # 获取数据类型
                    dataType = str(row_types[j])
                    type = dataType.split("'")[1]
                    #print(str(title_de))
                    #删除"'"字符
                    title_cn = title_de.split("'")[1]
                    # 获取单元格的值
                    resulat_tip = GetValue(type,sheet.row_values(i)[j])
 
                    temp[title_cn] = resulat_tip
 
                result[result_file_name].append(temp)
            #dumps 参数说明
            #indent 缩进字符数
            #sort_keys 是否对字段进行排序
            json_data = json.dumps(result, indent=4, sort_keys=False)
            #保存数据
            saveFile(str(os.getcwd()+outpath), str(result_file_name), json_data)
 
def GetValue(type,oldValues):
    #print("type::"+str(type))
    if type == "Int":
        return int(oldValues)
    if type == 'String':
        return str(oldValues)
    if type == 'Float':
        return float(oldValues)
    if type == 'Boolean':
        if oldValues == 1:
            return  True
        else:
            return  False
 
 
#判断是否有重复字段
def IsHaveRepeatFiel(data):
    is_have = False
    #获取所有字段数组
    tempData = []
    index = 0
    for in data:
        tempData.append(str(d).split("'")[1])
    #字段个数统计
    countDict = {}
    for x in set(tempData):
        countDict[x] = list.count(tempData,x)
    #print(str(countDict))
    #判断是不有重复字段
    for temp in countDict:
        if countDict[temp]>1:
            is_have = True
            print("重复字段:"+str(temp))
    return is_have
#获取数据
def get_data(file_path):
    try:
        data = xlrd.open_workbook(file_path)
        return data
    except Exception as e:
        print("获取excel数据表错误:" + file_path)
        print(str(e))
        return None
 
#保存文件
def saveFile(file_path, file_name, data):
    print(str("保存文件:"+file_path + "/" + file_name + ".json"))
 
    if os.path.exists(file_path) != True:
        #创建文件夹out
        os.makedirs(file_path)
 
    output = codecs.open(file_path + "/" + file_name + ".json", 'w', "utf-8")
    output.write(data)
    output.close()
 
#获取目录下所有文件
def getListFiles(path):
    ret = []
    for root, dirs, files in os.walk(path):
        for filespath in files:
            ret.append(os.path.join(root, filespath))
    return ret
 
 
if __name__ == '__main__':
    print("current Path:"+application_path)
    os.chdir(application_path)
    ret = []
    if isEXE:
        ret = getListFiles(application_path+"/files")
    else:
        ret = getListFiles("./files")
    for file_path in ret:
        if file_path.endswith(".xlsx") or file_path.endswith(".xls"):
            json_data = ExcelToJson(file_path)
    print("数据导出成功!!!")


最后附上Mac版可执行文件:http://www.manew.com/forum.php?mod=attachment&aid=MTQ0MjY0fDM1OGRjN2VmNTYyNmUxM2NlNmZkNDUxMDBmYzRmMWI4fDE1MTI1MjQyMzE%3D&request=yes&_f=.zip