excel表格格式 说明: 1.前三行分别为:字段中文解释、字段名、字段类型 2.程序不用的字段,加”_”前缀,不会生成进lua文件里 3.策划填数值的时候,偶尔会遗漏数据,当存在空值时,依据字段类型,填上默认值。 4.支持一个字段填上多组数据,如”进阶消耗”字段,自定义类型”table”,代表{ {道具1id,道具1数量},{道具2id,道具2数量}}, … } 脚本文件目录结构 windows bat命令,用于快速执行excel2lua.py脚本 excel2lua.py脚本代码 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+