python3將excel xlsx 轉爲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文件合法性





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章