美文网首页
unity3d-excel导表工具,导出到cs脚本

unity3d-excel导表工具,导出到cs脚本

作者: 伏波Rinnsio1xy | 来源:发表于2018-12-16 22:37 被阅读10次

网络上的搜索太多相关导表工具,u3d的很多且很杂,lua版本的其实很简单,cs版本的主要是需要构建对象相对复杂一点点,我把以前的一个导lua配置表的工具做了修改,花了半天时间。

一、python脚本导表工具

目前工具以及有js,lua版本,目前的项目是个小项目且用的时cs脚本,所以我打算直接将excel表格的配置数据导出的cs脚本使用。

二、导出的代码格式【DataMgr】和【所以表构建的类】

DataMgr.cs

初始所有配置表,获取对应的表
public static class DataMgr
{
    public static circle_mode circle_mode ;
    public static color2_level color2_level ;
    public static boss boss ;
    public static slider_mode slider_mode ;
    public static difficulty difficulty ;
    public static globalConfig globalConfig ;
    public static circle_level circle_level ;
    public static color2_mode color2_mode ;
    public static level level ;

    public static void load()
    {
        circle_mode = new circle_mode();
        circle_mode.load();
        color2_level = new color2_level();
        color2_level.load();
        boss = new boss();
        boss.load();
        slider_mode = new slider_mode();
        slider_mode.load();
        difficulty = new difficulty();
        difficulty.load();
        globalConfig = new globalConfig();
        globalConfig.load();
        circle_level = new circle_level();
        circle_level.load();
        color2_mode = new color2_mode();
        color2_mode.load();
        level = new level();
        level.load();

    }
}
导出的某个配置表类的结构

/*******************************************
gen by py tools
author:lyn
*******************************************/
using System;
using System.Reflection;
using System.Collections.Generic;
public class color2_level 
{
    public int id;
    public int condition;
    public int con_value;
    public float speed_rate;
    public int drop_speed_limit;
    public int speed_eliminate_limit;
    public List<float> color2_color= new List<float>();
    public List<int> monster_id= new List<int>();
    public int heavy_num;
    public float special_box_rate;
    public List<int> special_box_weight= new List<int>();

    public color2_level(  int _id, int _condition, int _con_value, float _speed_rate, int _drop_speed_limit, int _speed_eliminate_limit, List<float> _color2_color, List<int> _monster_id, int _heavy_num, float _special_box_rate, List<int> _special_box_weight)
    {
        id = _id;
        condition = _condition;
        con_value = _con_value;
        speed_rate = _speed_rate;
        drop_speed_limit = _drop_speed_limit;
        speed_eliminate_limit = _speed_eliminate_limit;
        color2_color = _color2_color;
        monster_id = _monster_id;
        heavy_num = _heavy_num;
        special_box_rate = _special_box_rate;
        special_box_weight = _special_box_weight;
    
    }
}
public class color2_level_Data
{
    private  Dictionary<int, color2_level> m_dataDic = new Dictionary<int, color2_level>();
    public void load()
    {
        m_dataDic.Add(11, new color2_level(11,1,200,1.5f,300,310,new List<float>(){0.0f, 1.0f},new List<int>(){1, 2},1,0.0f,new List<int>(){0, 0}));
        m_dataDic.Add(12, new color2_level(12,1,400,1.5f,300,310,new List<float>(){0.0f, 2.0f},new List<int>(){1, 3},1,0.1f,new List<int>(){0, 1}));
        m_dataDic.Add(13, new color2_level(13,2,30,1.75f,300,310,new List<float>(){1.0f, 2.0f},new List<int>(){2, 3},1,0.1f,new List<int>(){0, 1}));
        m_dataDic.Add(14, new color2_level(14,1,600,1.75f,300,310,new List<float>(){0.0f, 1.0f, 3.0f},new List<int>(){1, 2},2,0.1f,new List<int>(){0, 1}));
        m_dataDic.Add(15, new color2_level(15,1,1000,1.75f,300,310,new List<float>(){0.0f, 2.0f, 4.0f},new List<int>(){1, 3},2,0.1f,new List<int>(){0, 1}));
        m_dataDic.Add(16, new color2_level(16,2,45,2.0f,300,310,new List<float>(){1.0f, 2.0f, 5.0f},new List<int>(){2, 3},2,0.1f,new List<int>(){0, 1}));
        m_dataDic.Add(17, new color2_level(17,1,2000,2.0f,300,310,new List<float>(){0.0f, 1.0f, 2.0f},new List<int>(){1, 2, 3},1,0.1f,new List<int>(){0, 1}));
        m_dataDic.Add(18, new color2_level(18,2,45,2.0f,300,310,new List<float>(){0.0f, 1.0f, 2.0f, 3.0f, 4.0f, 5.0f},new List<int>(){1, 2, 3},2,0.1f,new List<int>(){0, 1}));
        m_dataDic.Add(19, new color2_level(19,2,60,2.15f,300,310,new List<float>(){0.0f, 1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f},new List<int>(){1, 2, 3},3,0.1f,new List<int>(){0, 1}));
        m_dataDic.Add(110, new color2_level(110,2,60,2.15f,300,310,new List<float>(){0.0f, 1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f},new List<int>(){1, 2, 3},3,0.1f,new List<int>(){0, 1}));

    }
    public Dictionary<int, color2_level> getAllData()
    {
        return m_dataDic;
    }
    public color2_level getDataById(int id)
    {
        return m_dataDic[id];
    }
}

三、excel表的结构

配置表支持的数据类型,目前我觉得够用的类型是:
int:int
float:float
string:string
arrary_int:List<int>
array_float:List<float>
array_string:List<string>
image.png

四�、python工具代码

使用此脚本需要安装xlrd模块!需要用到的json配置

config_path:excel目录
output_path:导出的目录

{
"config_path" : "./data",
"output_path" : "./out/"
}

# -*- coding:utf-8 -*-
import xlrd
import json
import os
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
# book = xlrd.open_workbook("ceshi.xlsx")
# sheet = book.sheet_by_index(0)
# print sheet.name, sheet.nrows, sheet.ncols
# #获取整行相关的内容
# print sheet.row_values(1)
# print sheet.row_values(2)
# print sheet.row_values(3)
# print sheet.row_values(4)
# config_path = "G:\\shadowsight\\策划文档\\配置表"
# output_path = "G:\\shadowsight\\demo\\src\\app\\data\\"

#with open("config.json", "rb") as fp:
fp = open("./config.json", "rb")
print("out config:", fp)
jsonObj = json.load(fp)

config_path = jsonObj.get('config_path')
output_path = jsonObj.get('output_path')
special_list = {}#jsonObj.get('special')
ignor_list = {} #jsonObj.get('ignore')

FiledType = {"int" : "int", "float": "float", "string":"string", "array_float":"List<float>", "array_int":"List<int>", "array_string":"List<string>"}

#格式化:数据类名字,数据类参数,数据类名字, 数据类构造函数参数, 数据类赋值, 数据主类名, 数据类名字,添加数据,
cs_header ='''
/*******************************************
gen by py tools
author:lyn
*******************************************/
using System;
using System.Reflection;
using System.Collections.Generic;
public class {0} 
<|
    {1}
    public {2}( {3} )
    <|
        {4}
    |>
|>
public class {5}
<|
    private  Dictionary<int, {6}> m_dataDic = new Dictionary<int, {6}>();
    public void load()
    <|
        {7}
    |>
    public Dictionary<int, {6}> getAllData()
    <|
        return m_dataDic;
    |>
    public {6} getDataById(int id)
    <|
        return m_dataDic[id];
    |>
|>'''
    

def __convert_real_value(_type, value, col):
    #print("cur column" + str(col) + " filed:"+ _type)
    _type = _type.replace(" ", "")
    if _type == "number" or _type == "int":
        if value == '':
            return str(int(0))
        return str(int(value))
    if _type == "string":
        return '"' + str(value) + '"'
    if _type == "float":
        if value == '':
            return str(int(0)) + "f"

        return str(float(value)) +"f"
    if _type == "array_float": #List<float>
        value = str(value)
        value = value.replace(' ', "")
        if value == '':
            return "new List<float>()"

        value_list = value.split(',')
        ret_list = []
        for value in value_list:
            ret_list.append(str(float(value)) + "f")


        retStr = json.dumps(ret_list)
        retStr = retStr.replace('[', '{')
        retStr = retStr.replace(']', '}')
        retStr = retStr.replace('"', '')
        return "new List<float>()" + retStr       
    if _type == "array_int": #List<int>
        value = str(value)
        value = value.replace(' ', "")
        if value == '':
            return "new List<int>(){}"

        value_list = value.split(',')
        ret_list = []
        for value in value_list:
            ret_list.append(int(float(value)))

        retStr = json.dumps(ret_list)
        retStr = retStr.replace('[', '{')
        retStr = retStr.replace(']', '}')
        return "new List<int>()" + retStr
    if _type == "array_string": #List<string>
        value = str(value)
        value = value.replace(' ', "")
        if value == '':
            return "new List<string>(){}"

        value_list = value.split(',')
        length = len(value_list)
        ret_list = []
        retStr = '{'
        index = 0
        for value in value_list:
            retStr += '"' + str(value) + '"'
            index += 1
            if index != length:
                retStr += ","
        retStr += '}'      
        return "new List<string>()" + retStr
    assert False

def gen_class_params(_type, filedName):  
    classParams = "public " + FiledType[_type] + " " + filedName 
    if _type == "array_float": #List<float>
        classParams = classParams + "= new List<float>()" 
    if _type == "array_int": #List<int>
        classParams = classParams + "= new List<int>()" 
    if _type == "array_string": #List<string>
        classParams = classParams + " = new List<string>()" 
    
    return classParams+ ";\n   "

def export_normal(tableName):
    print('解析表:' + tableName)
    book = xlrd.open_workbook( config_path +"/"+tableName + ".xlsx")
    sheet = book.sheet_by_index(0)
    nrows, ncols = sheet.nrows, sheet.ncols
    
    #表单字段
    tableNames = sheet.row_values(1)
    #表单类型名称
    typeNames = sheet.row_values(2)
    className = tableName # 类名
    classMasterName = tableName + "_Data"
    constructParams = "" #构造函数参数
    classParams = ""
    setParamsStr = ""
    l = len(tableNames)
    for x in xrange(0, l):
        if typeNames[x] != "none":
            classParams = classParams + gen_class_params(typeNames[x], tableNames[x]) +""
            constructParams = constructParams + " " + FiledType[typeNames[x]] + " " + "_" + tableNames[x] + ","    
            setParamsStr = setParamsStr + tableNames[x] +" = " + "_" + tableNames[x] + ";\n\t"

    print("classParams:", classParams)
    

    tables = {}
    #表单实际内容
    for i in range(3, nrows):
        oneData = sheet.row_values(i)
        defineId = int(oneData[0])

        tables[defineId] = {}
        _value = ""
        for j in range(ncols):
            key = tableNames[j]
            _type = typeNames[j]
            if _type != "none":
                _value = _value + __convert_real_value(_type, oneData[j], i) +","
                #tables[defineId][key] = value
        tables[defineId] = _value
        print("_value",_value)

    out_p = output_path + tableName + ".cs"
    out_data = ""
    saveStr = ""
    with open(out_p, "w") as fp:
        for defineid, smalltabs in tables.items():
            saveStr = saveStr + "m_dataDic.Add({0}, ".format(defineid) + "new "+className + "(" + smalltabs+"));\n"

    lastStr = cs_header.format(className, classParams, className, constructParams, setParamsStr, classMasterName, className, saveStr)
    lastStr = lastStr.replace('<|', '{')
    lastStr = lastStr.replace('|>', '}')
    lastStr = lastStr.replace(',)', ')')
    lastStr = lastStr.replace(', )', ')')
    lastStr = lastStr.replace('),', ')')
    
    #print(lastStr)
    fp = open(out_p, "w")
    fp.write(lastStr)

def export_same_id(tableName):
    print("解析表" + tableName)
    book = xlrd.open_workbook(tableName + '.xlsx')
    sheet = book.sheet_by_index(0)
    nrows, ncols = sheet.nrows, sheet.ncols

    tableNames = sheet.row_values(1)
    typeNames = sheet.row_values(2)

    tables = {}
    for i in range(3, nrows):
        #print("当前行数" + str(i))
        oneData = sheet.row_values(i)
        defineId = int(oneData[0])

        if tables.get(defineId) == None:
            tables[defineId] = {}

        tempDict = {}
        small_id = None
        for j in range(ncols):
            key = tableNames[j]
            _type = typeNames[j]
            if _type != "none":
                value = __convert_real_value(_type, oneData[j], j)
                tempDict[key] = value
            if _type != "none" and key == "small_id":
                small_id = __convert_real_value(_type, oneData[j], j)

        assert(small_id)
        tables[defineId][int(float(small_id))] = tempDict
        
    with open(output_path + tableName + ".js", "w", encoding='utf-8') as fp:
        fp.write("var " + tableName + "= {\n")
        for defineid, smalltabs in tables.items():
            saveStr = "[{0}] : ".format(defineid) + "["

            for key, value in smalltabs.items():
                saveStr += str(key) + ":" + value + ","
            saveStr += "],\n"
            fp.write(saveStr)

        fp.write("}\n")
        fp.write("exports = module.exports = " + tableName) 

def export_same_id(tableName):
    print("parse table" + tableName)
    book = xlrd.open_workbook(config_path + tableName + '.xlsx')
    sheet = book.sheet_by_index(0)
    nrows, ncols = sheet.nrows, sheet.ncols

    tableNames = sheet.row_values(1)
    typeNames = sheet.row_values(2)

    tables = {}
    for i in range(3, nrows):
        oneData = sheet.row_values(i)
        defineId = int(oneData[0])

        if tables.get(defineId) == None:
            tables[defineId] = {}

        tempDict = {}
        small_id = None
        for j in range(ncols):
            key = tableNames[j]
            _type = typeNames[j]
            if _type != "none":
                value = __convert_real_value(_type, oneData[j], j)
                tempDict[key] = value
            if _type != "none" and key == "small_id":
                small_id = __convert_real_value(_type, oneData[j], j)

        assert(small_id)
        tables[defineId][int(float(small_id))] = tempDict
        
    with open(output_path + tableName + ".js", "w", encoding='utf-8') as fp:
        fp.write("var " + tableName + "= {\n")
        for defineid, smalltabs in tables.items():
            saveStr = "[{0}] : ".format(defineid) + "{"

            for key, valueDict in smalltabs.items():
                saveStr += "[{0}] : ".format(key) + "{"
                for skey, value in valueDict.items():
                    saveStr += str(skey) + ":" + value + ","
                saveStr += "},"
            saveStr += "},\n"
            fp.write(saveStr)

        fp.write("}\n")
        fp.write("exports = module.exports = " + tableName) 

if __name__ == '__main__':
    export_file_list = []
    for root, dirs, files in os.walk(config_path):
        for file in files:
            path = os.path.join(root, file)
            _, ext = os.path.splitext(path)
            _, fileName = os.path.split(path)
            if ext == ".xlsx" and fileName.find('~') == -1:
                export_file_list.append(fileName)

    for file in export_file_list:
        fileName = file.replace('.xlsx', '')
        if fileName in special_list:
            export_same_id(fileName)
        else:
            export_normal(fileName)

    #import os
    #os.system("pause")

五、生成DataMgr.cs的脚本

# -*- coding:utf-8 -*-
import xlrd
import json
import os
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
# file  : gen_data_script.py
# author: lyn
# date  : 2018-08-31

import re 
import os

CLINT_NAME = "DataMgr.cs"
SERVER_NAME = "DataSMgr.js"
out_to_client_file = open(CLINT_NAME, "w+")
out_to_client_file.writelines("")

out_to_server_file = open(SERVER_NAME, "w+")
out_to_server_file.writelines("")

global classParams
global constructorParams

classParams = ""
constructorParams = ""
global client_str
client_str = '''public static class DataMgr
<|
    {0}
    public static void load()
    <|
        {1}
    |>
|>'''

def file_name(file_dir):   
    for root, dirs, files in os.walk(file_dir):
        return files


all_file = file_name("./out")


def gen_tables():
    global classParams
    global constructorParams
    global client_str
    for name in all_file: 
        file_name = os.path.splitext(name)[0]
        ext =os.path.splitext(name)[1] 
        if ext == ".cs":
            classParams = classParams +"public static "+ file_name+"_Data" + " " + file_name + " ;\n"
            constructorParams = constructorParams + file_name + " = new " + file_name+"_Data();\n" + file_name+".load();\n"
            print("file_name:", file_name, ext)

gen_tables()
client_str = client_str.format(classParams, constructorParams)
client_str = client_str.replace("<|", "{")
client_str = client_str.replace("|>", "}")
print("client_str:", client_str)
out_to_client_file.writelines(client_str)

喜欢就点个星呗!

相关文章

网友评论

      本文标题:unity3d-excel导表工具,导出到cs脚本

      本文链接:https://www.haomeiwen.com/subject/bskfkqtx.html