根据Excal表生成代码

Excal格式要求

第一行是类型名   第二行是类型

例如: string  name;   string是类型,name是类型名。

具体代码

    [MenuItem("Tools/ExcalToModel.cs")]
    public static void GenerationModel()
    {

        string selectPath = AssetDatabase.GetAssetOrScenePath(Selection.activeObject);

        Debug.Log(selectPath);
        string className = selectPath.Substring(selectPath.LastIndexOf('/') + 1, selectPath.LastIndexOf('.') - selectPath.LastIndexOf('/') - 1);
        string fileName = className + ".cs";
        string[] name;
        string[] pro;
        //读取Excal
        using (FileStream fs = File.Open(selectPath, FileMode.Open))
        {
            IExcelDataReader excelDataReader = ExcelReaderFactory.CreateOpenXmlReader(fs);
            DataSet dataSet = excelDataReader.AsDataSet();
            int cow = dataSet.Tables[0].Columns.Count;
            name = new string[cow];  //名字
            pro = new string[cow];     //类型
            for (int i = 0; i < cow; i++)
            {
                name[i] = dataSet.Tables[0].Rows[0][i].ToString();
                pro[i] = dataSet.Tables[0].Rows[1][i].ToString();
                Debug.Log("name="+ name[i]+"_____"+"pro="+pro[i]);
            }
        }
        string path = Application.dataPath + "/Scripts/Model/";
        if (!System.IO.Directory.Exists(path))
        {
            System.IO.Directory.CreateDirectory(path);
        }
        path += fileName;
        if (File.Exists(path))
            File.Delete(path);
        using (FileStream fs = File.Open(path, FileMode.OpenOrCreate))
        {
            string code = "using System;
" +
                " 
" +
            $"public class {className}
" +
            "{
";
            for (int i = 0; i < name.Length; i++)
            {
                code += $"    public {pro[i]} {name[i]}"+ "{get;set;}
";
            }
            code += "}
";
            fs.Write(System.Text.UTF8Encoding.UTF8.GetBytes(code),0, System.Text.UTF8Encoding.UTF8.GetBytes(code).Length);
        }
        AssetDatabase.SaveAssets();
        AssetDatabase.Refresh();
    }

使用方式

文件夹选中需要生成的Excal(excal后缀名必须是xlsx才可以用IExcelDataReader 读取),点击Tools/ExcalToModel.cs 。

生成结果

using System;
 
public class WarSkill
{
    public string name{get;set;}
    public int damage{get;set;}
    public int coolDown{get;set;}
    public SkillType SkillType{get;set;}
    public int duringTime{get;set;}
    public int SuperArmordefense{get;set;}
    public int SuperArmorAttack{get;set;}
    public int SkilPoint{get;set;}
    public Element Element{get;set;}
    public string describe{get;set;}
}
原文地址:https://www.cnblogs.com/DazeJiang/p/14349173.html