• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

使用Python实现Excel转Lua、Json

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

转自:http://www.u3d8.com/?p=1860

本文主要是介绍自己前几天做的工具,是可以批量将Excel转成Lua和Json格式

工具操作比较简单,这里不再介绍操作方法

注:目前支持的Excel格式为.xls文件,如果是.xlsx文件,记得使用之前转下格式

操作界面:

主要代码:

import Excel
import os
import threading
import cgitb
 
keyRow = 0
valueTypeRow = 1
luaOrJsonRow = 2
descriptionRow = 3
valueRowBegin = 4
 
 
convertType = {
    'Ignore': 0,
    'Lua': 1,
    'Json': 2,
    'All': 3,
}
 
 
class Execute():
    def do(self,mainController, excelFolderPath, luaFolderPath, jsonFolderPath):
        cgitb.enable(format = 'text')
        print('************************** 开始 ********************************')
        print("Excel:"+ excelFolderPath)
        print("Lua:"+ luaFolderPath)
        print("Json:"+ jsonFolderPath)
        self.mainController = mainController
        self.excelFolderPath = excelFolderPath
        self.luaFolderPath = luaFolderPath
        self.jsonFolderPath = jsonFolderPath
        self.mainController.setConfirmState(False)
 
        # self.thread = threading.Thread(target=self.doThread)
        # self.thread.setDaemon(True)
        # self.thread.start()
        self.doThread()
 
    def doThread(self):
        print()
        self.progressValue = 0
        self.mainController.mainView.progressBar.setValue(self.progressValue)
        self.getExcelFiles()
        self.toLua()
        self.toJson()
        print()
        print('************************** 完成 ********************************')
        self.mainController.setConfirmState(True)
        # self.mainController.finishBox()
 
    def getExcelFiles(self):
        self.excelFiles = []
        for parent, _dirNames, _fileNames in os.walk(self.excelFolderPath):
            for fileName in _fileNames:
                if(fileName.split('.')[-1] == "xls"):
                    self.excelFiles.append(self.excelFolderPath + "/" + fileName)
        print('\n************** Excel Files ***************')
        print(self.excelFiles)
 
    def toLua(self):
        print('\n************** ToLua ***************')
        for excelFile in self.excelFiles:
            sheetNames = Excel.getSheetNames(excelFile)
            for sheetName in sheetNames:
                print('开始转换Lua:'+ sheetName)
                luaData = sheetName + "={"
                keys = Excel.readRow(excelFile, sheetName, keyRow)
                valueTypes = Excel.readRow(excelFile, sheetName, valueTypeRow)
                luaOrJsons = Excel.readRow(excelFile, sheetName, luaOrJsonRow)
                excelData = Excel.readAll(excelFile, sheetName)
                lastValidTypeIndex = 0;
                for i in range(0, len(luaOrJsons)):
                    if(str(luaOrJsons[i]) == str(convertType['Lua']) or str(luaOrJsons[i]) == str(convertType['All'])):
                        lastValidTypeIndex = i
                validKeys = []
                for i in range(valueRowBegin+1, len(excelData)):
                    for j in range(0, len(excelData[i])):
                        if(excelData[i][0] == None or excelData[i][0] == ""): continue
                        if(luaOrJsons[j] == None or luaOrJsons[j] == ""): continue
                        if(str(luaOrJsons[j]) != str(convertType['Lua']) and str(luaOrJsons[j]) != str(convertType['All'])): continue
                        if(j == 0):
                            if(valueTypes[0] == 'int'):
                                luaData += '\n\t[' + str(excelData[i][j]) + '] = {'
                            else:
                                luaData += '\n\t["' + str(excelData[i][j]) + '"] = {'
 
                        if(valueTypes[j] == 'int'):
                            luaData += '\n\t\t' + keys[j] + ' = ' + str(excelData[i][j]) + ','
                        elif(valueTypes[j] == 'float'):
                            luaData += '\n\t\t' + keys[j] + ' = ' + str(excelData[i][j]) + ','
                        elif(valueTypes[j] == 'double'):
                            luaData += '\n\t\t' + keys[j] + ' = ' + str(excelData[i][j]) + ','
                        elif(valueTypes[j] == 'string'):
                            luaData += '\n\t\t' + keys[j] + ' = "' + str(excelData[i][j]) + '",'
                        elif(valueTypes[j] == 'array'):
                            luaData += '\n\t\t' + keys[j] + ' = {' + str(excelData[i][j]) + '},'
                        else:
                            luaData += '\n\t\t' + keys[j] + ' = ' + str(excelData[i][j]) + ','
 
                        if(j == lastValidTypeIndex):
                            luaData += '\n\t},'
 
                        if(validKeys.__contains__(excelData[i][0]) == False):
                            validKeys.append(excelData[i][0])
                luaData += '\n}'
 
                luaData += '\n' + sheetName + '.keys={'
                for i in range(0, len(validKeys)):
                    if (valueTypes[0] == 'int'):
                        luaData += str(int(validKeys[i]))
                    else:
                        luaData += str(validKeys[i])
                    if (i < len(validKeys)-1):
                        luaData += ','
                    else:
                        luaData += '}'
 
                print('转换完成Lua:'+ sheetName)
                if not os.path.exists(self.luaFolderPath):
                    os.makedirs(self.luaFolderPath)
                file = open(self.luaFolderPath + "/" + sheetName + '.lua', 'w')
                file.write(luaData)
                file.close()
 
                self.progressValue += 100 / (len(sheetNames) * 2)
                self.mainController.mainView.progressBar.setValue(self.progressValue)
 
    def toJson(self):
        print('\n************** ToJson ***************')
        for excelFile in self.excelFiles:
            sheetNames = Excel.getSheetNames(excelFile)
            for sheetName in sheetNames:
                print('开始转换Json:' + sheetName)
                jsonData = "{"
                jsonData += '\n\t' + '"datas":['
                keys = Excel.readRow(excelFile, sheetName, keyRow)
                valueTypes = Excel.readRow(excelFile, sheetName, valueTypeRow)
                luaOrJsons = Excel.readRow(excelFile, sheetName, luaOrJsonRow)
                excelData = Excel.readAll(excelFile, sheetName)
                lastValidTypeIndex = 0
                for i in range(0, len(luaOrJsons)):
                    if (str(luaOrJsons[i]) == str(convertType['Json']) or str(luaOrJsons[i]) == str(convertType['All'])):
                        lastValidTypeIndex = i
                validKeys = []
                for i in range(valueRowBegin + 1, len(excelData)):
                    for j in range(0, len(excelData[i])):
                        if (excelData[i][0] == None or excelData[i][0] == ""): continue
                        if (luaOrJsons[j] == None or luaOrJsons[j] == ""): continue
                        if (str(luaOrJsons[j]) != str(convertType['Json']) and str(luaOrJsons[j]) != str(
                            convertType['All'])): continue
                        if (j == 0):
                            jsonData += '\n\t\t{'
 
                        if (valueTypes[j] == 'int'):
                            jsonData += '\n\t\t\t"' + keys[j] + '" : ' + str(excelData[i][j])
                        elif (valueTypes[j] == 'float'):
                            jsonData += '\n\t\t\t"' + keys[j] + '" : ' + str(excelData[i][j])
                        elif (valueTypes[j] == 'double'):
                            jsonData += '\n\t\t\t"' + keys[j] + '" : ' + str(excelData[i][j])
                        elif (valueTypes[j] == 'string'):
                            jsonData += '\n\t\t\t"' + keys[j] + '" : "' + str(excelData[i][j]) + '"'
                        elif (valueTypes[j] == 'array'):
                            jsonData += '\n\t\t\t"' + keys[j] + '" : [' + str(excelData[i][j]) + ']'
                        else:
                            jsonData += '\n\t\t\t"' + keys[j] + '" : ' + str(excelData[i][j])
 
                        if (j == lastValidTypeIndex):
                            jsonData += '\n\t\t}'
                            if(i != len(excelData)-1):
                                jsonData += ','
                        else:
                            jsonData += ','
 
                        if (validKeys.__contains__(excelData[i][0]) == False):
                            validKeys.append(excelData[i][0])
 
                jsonData += '\n\t' + ']'
                jsonData += '\n' + '}'
 
                print('转换完成Json:' + sheetName)
                if not os.path.exists(self.jsonFolderPath):
                    os.makedirs(self.jsonFolderPath)
                file = open(self.jsonFolderPath + "/" + sheetName + '.json', 'w')
                file.write(jsonData)
                file.close()
 
                self.progressValue += 100 / (len(sheetNames) * 2)
                self.mainController.mainView.progressBar.setValue(self.progressValue)
 
    def toJson2(self):
        print('\n************** ToJson ***************')
        for excelFile in self.excelFiles:
            sheetNames = Excel.getSheetNames(excelFile)
            for sheetName in sheetNames:
                print('开始转换Json:' + sheetName)
                jsonData = {}
                keys = Excel.readRow(excelFile, sheetName, keyRow)
                valueTypes = Excel.readRow(excelFile, sheetName, valueTypeRow)
                luaOrJsons = Excel.readRow(excelFile, sheetName, luaOrJsonRow)
                excelData = Excel.readAll(excelFile, sheetName)
                for i in range(valueRowBegin + 1, len(excelData)):
                    key = excelData[i][0]
                    jsonData[key] = {}
                    for j in range(0, len(excelData[i])):
                        if (excelData[i][0] == None or excelData[i][0] == ""): continue
                        if (luaOrJsons[j] == None or luaOrJsons[j] == ""): continue
                        if (str(luaOrJsons[j]) != str(convertType['Json']) and str(luaOrJsons[j]) != str(
                            convertType['All'])): continue
                        jsonData[key][keys[j]] = excelData[i][j]
 
                jsonData = json.dumps(jsonData)
                print('转换完成Json:' + sheetName)
                if not os.path.exists(self.jsonFolderPath):
                    os.makedirs(self.jsonFolderPath)
                file = open(self.jsonFolderPath + "/" + sheetName + '.json', 'w')
                file.write(jsonData)
                file.close()
 
                self.progressValue += 100 / (len(sheetNames) * 2)
                self.mainController.mainView.progressBar.setValue(self.progressValue)

 


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Lua学习一----------开发环境搭建发布时间:2022-07-22
下一篇:
openresty 中使用lua 的页面模板类库template来渲染页面发布时间:2022-07-22
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap