python3将excel xlsx 转为lua文件_xlsx转换成lua-程序员宅基地

技术标签: python  大话技术  lua  

excel表格格式  
说明: 
1.前三行分别为:字段中文解释、字段名、字段类型 
2.程序不用的字段,加”_”前缀,不会生成进lua文件里 
3.策划填数值的时候,偶尔会遗漏数据,当存在空值时,依据字段类型,填上默认值。 

4.支持一个字段填上多组数据,自定义类型”table”,代表{ {id1,数量},{id2,数量}}, … } 



excel2lua.py脚本代码

# -*- coding: UTF-8 -*- 
import sys
import os
import xlrd
import re

# 当前脚本路径
curpath = os.path.dirname(os.path.abspath(sys.argv[0]))

# 文件头描述格式化文本
lua_file_head_format_desc = '''--[[

        %s
        exported by excel2lua.py
        from file:%s

--]]\n\n'''

# 将数据导出到tgt_lua_path
def excel2lua(src_excel_path, tgt_lua_path):
    print('[file] %s -> %s' % (src_excel_path, tgt_lua_path))
    # load excel data
    excel_data_src = xlrd.open_workbook(src_excel_path, encoding_override = 'utf-8')
    print('[excel] Worksheet name(s):', excel_data_src.sheet_names())
    excel_sheet = excel_data_src.sheet_by_index(0)
    print('[excel] parse sheet: %s (%d row, %d col)' % (excel_sheet.name, excel_sheet.nrows, excel_sheet.ncols))

    # excel data dict
    excel_data_dict = {}

    # col name list
    col_name_list = []

    #col val type list
    col_val_type_list = []

    # ctype: 0 empty, 1 string, 2 number, 3 date, 4 boolean, 5 error

    # 遍历第二行的所有列 保存字段名
    for col in range(0, excel_sheet.ncols):
        cell = excel_sheet.cell(1, col)
        col_name_list.append(str(cell.value))
        assert cell.ctype == 1, "found a invalid col name in col [%d] !~" % (col)

    # 遍历第三行的所有列 保存数据类型
    for col in range(0, excel_sheet.ncols):
        cell = excel_sheet.cell(2, col)
        col_val_type_list.append(str(cell.value))
        assert cell.ctype == 1, "found a invalid col val type in col [%d] !~" % (col)

    # 剔除表头、字段名和字段类型所在行 从第四行开始遍历 构造行数据
    for row in range(3, excel_sheet.nrows):
        # 保存数据索引 默认第一列为id
        cell_id = excel_sheet.cell(row, 0)

        assert cell_id.ctype == 2, "found a invalid id in row [%d] !~" % (row)

        # 检查id的唯一性
        if cell_id.value in excel_data_dict:
            print('[warning] duplicated data id: "%d", all previous value will be ignored!~' % (cell_id.value))

        # row data list
        row_data_list = []

        # 保存每一行的所有数据
        for col in range(0, excel_sheet.ncols):
            cell = excel_sheet.cell(row, col)
            k = col_name_list[col]
            cell_val_type = col_val_type_list[col]

            # ignored the string that start with '_'
            if str(k).startswith('_'):
                continue

            # 根据字段类型去调整数值 如果为空值 依据字段类型 填上默认值
            if cell_val_type == 'string':
                if cell.ctype == 0:
                    v = '\'\''
                else:
                    v = '\'%s\'' % (cell.value)
            elif cell_val_type == 'int':
                if cell.ctype == 0:
                    v = -1
                else:
                    v = int(cell.value)
            elif cell_val_type == 'float':
                if cell.ctype == 0:
                    v = -1
                else:
                    v = float(cell.value)
            elif cell_val_type == 'table':
                if cell.ctype == 0:
                    v = '{}'
                else:
                    v = cell.value
            else:
                v = cell.value

            # 加入列表
            row_data_list.append([k, v])

        # 保存id 和 row data
        excel_data_dict[cell_id.value] = row_data_list

    # 正则搜索lua文件名 不带后缀 用作table的名称 练习正则的使用
    searchObj = re.search(r'([^\\/:*?"<>|\r\n]+)\.\w+$', tgt_lua_path, re.M|re.I)
    lua_table_name = searchObj.group(1)
    # print('正则匹配:', lua_table_name, searchObj.group(), searchObj.groups())

    # 这个就直接获取文件名了
    src_excel_file_name = os.path.basename(src_excel_path)
    tgt_lua_file_name = os.path.basename(tgt_lua_path)

    # file head desc
    lua_file_head_desc = lua_file_head_format_desc % (tgt_lua_file_name, src_excel_file_name)

    # export to lua file
    lua_export_file = open(tgt_lua_path, 'w')
    lua_export_file.write(lua_file_head_desc)
    lua_export_file.write('%s = {\n' % lua_table_name)

    # 遍历excel数据字典 按格式写入
    for k, v in excel_data_dict.items():
        lua_export_file.write('  [%d] = {\n' % k)
        for row_data in v:
            lua_export_file.write('   {0} = {1},\n'.format(row_data[0], row_data[1]))
        lua_export_file.write('  },\n')

    lua_export_file.write('}\n')

    lua_export_file.close()

    print('[excel] %d row data exported!~' % (excel_sheet.nrows))

# Make a script both importable and executable (∩_∩)
if __name__ == '__main__':
    if len(sys.argv) < 3:
        print('python excel2lua.py <excel_input_path> <lua_output_path>')
        exit(1)

    excel2lua(os.path.join(curpath, sys.argv[1]), os.path.join(curpath, sys.argv[2]))

    exit(0)

执行python命令截图




生成lua文件截图



测试lua文件合法性





版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/lake1314/article/details/80361503

智能推荐

Unity ShaderLab 中的内置变量_shaderlab 内置参数-程序员宅基地

文章浏览阅读1.5k次。点此获取官方文档地址所有的这些内置变量类型无需声明,直接使用,需要包含:UnityCG.cginc file.Transformationsfloat4x4 UNITYMATRIXMVP Current modelviewprojection matrixfloat4x4 UNITYMATRIXMV Current model*view matrixfloa_shaderlab 内置参数

MFC定义圆角矩形按钮_修改mfcgroupbox为圆角矩形-程序员宅基地

文章浏览阅读6.8k次。使用仅需两步!第一步:CButton替换为CBtnNoImg。第二步:设置各个状态的颜色,和字体(字体设置可选) { CFont *pFont = new CFont(); pFont->CreateFont(11, //以逻辑单位方式指定字体的高度 0, //以逻辑单位方式指定字体中字符的平均宽度 0, //指定偏离垂线和X轴在显示面上的夹角(单位:0.1_修改mfcgroupbox为圆角矩形

xml配置文件引用properties文件报错_xml文件找不到propertycommonconfigurer.class-程序员宅基地

文章浏览阅读1.6k次。一般是配置文件引用失败引起的正确的配置:<bean id="propertyConfigurer" class="com.jcl.common.spring.web.***PropertyPlaceholderConfigurer"> <property name="envPropFiles"> <lis..._xml文件找不到propertycommonconfigurer.class

Linux结构目录详解-程序员宅基地

文章浏览阅读1.1k次,点赞26次,收藏15次。Linux在Linux中,系统默认的用户是root,其实和 windows 的 administrator 类似,root 用户可以操作操作系统的任何文件和设备,所以在生产环境就不要乱用root了,权利越大,责任越大。学习Linux,就要习惯通过命令行的方式学习,。目前的Linux导图如下。

unity scrollview滚动到指定的位置_unity scrollview滚动到指定位置-程序员宅基地

文章浏览阅读2.8k次,点赞3次,收藏5次。unity scrollview 滚动到指定位置,需要使用 normalizedPosition,或者 verticalNormalizedPosition,或者 horizontalNormalizedPosition_unity scrollview滚动到指定位置

人脸识别技术优势-程序员宅基地

文章浏览阅读693次。当下人们对信息安全问题格外的注重,并且信息安全也成为这个时代的热门话题。基于密码、个人识别码、磁卡和钥匙等传统的安全措施已不能完全满足社会要求,所以人们把目光投向了生物特征识别技术——利用人体固有的生理特征或行..._人脸识别技术的优点

随便推点

汇编语言的简答入门--斐波那契数列(递归)_汇编语言递归求斐波那契-程序员宅基地

文章浏览阅读9k次。TITLE Save an array and dispalyINCLUDE Irvine32.inc.dataarray DWORD 12 DUP (?) ; define a array for saving Fibonacci numbersstep = type arraynum DWORD ?count DWORD ?prompt byte "The first_汇编语言递归求斐波那契

pip命令使用详解-程序员宅基地

文章浏览阅读10w+次,点赞29次,收藏188次。pip很像CentOS系统中的yum命令,用于安装及维护Python包。pip的安装windows其实在windows下是默认安装了pip工具的,只是没有将其所在目录加入Path,导致命令查找不到。 将python安装目录下的scripts目录加入环境变量Path中即可。Linux执行下面命令即可完成安装# wget https://bootstrap.pyp..._pip

2013.9.7 CISA pass的一点感想-程序员宅基地

文章浏览阅读68次。2013.9.7 CISA pass的一点感想 先说一个本人基本情况从事信息安全和BCM工作,考试前没有参加培训机构的培训,从6月中旬开始复习CISA,复习材料就是汇哲的教材书和2本红宝书。 看到论坛上各位大牛600+通过,我的通过分数4开头,就不拿出来show了,以免丢人现眼。在此就和大家分享几点个人复习和备考的感受。1、看到论坛上有大..._cisa 初步成绩报告 not pass

SpringSecurity的使用_spring security 3.7使用-程序员宅基地

文章浏览阅读3.9k次。Spring Security 是针对Spring项目的安全框架,也是Spring Boot底层安全模块默认的技术选型,他可以实现强大的Web安全控制,对于安全控制,我们仅需要引入 spring-boot-starter-security 模块,进行少量的配置,即可实现强大的安全管理!使用步骤:1:加入依赖 <dependency> <groupId>org.springframework.boot</groupId> _spring security 3.7使用

Linux 执行定时任务 shell脚本_linux定时任务shell脚本-程序员宅基地

文章浏览阅读540次。https://www.cnblogs.com/grimm/p/8794707.html Linux上面执行定时任务,我们可以利用crontab -e直接编辑定时任务 另外我们还可以写好shell脚本,定时去执行shell脚本,这两个方法都可以起到定时执行的作用下面我详细说一下入如何执行shell脚本1.声明一下我安装的lnmp环境,shell脚本存放的位置在 /usr/local..._linux定时任务shell脚本

给WordPress的文章插入数学公式_word公式在wordpress-程序员宅基地

文章浏览阅读5k次。这里是我的个人网站: https://endlesslethe.com/insert-math-formula-into-wordpress.html 有更多总结分享,最新更新也只会发布在我的个人网站上。排版也可能会更好看一点=v= 问题背景 我使用OneNote写总结。在总结数论相关的算法时,文章会包含数学公式。数学公式是MS特有的格式。直接将OneNote复制到WordPre_word公式在wordpress

推荐文章

热门文章

相关标签