Unity Excel转json且自动生成C#脚本

Unity Excel转json且自动生成C#脚本excel转json且自动生成c#脚本

大家好,又见面了,我是你们的朋友全栈君。

脚本:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using System.Windows.Forms; //必须是 Unity安装目录\Editor\Data\Mono\lib\mono\2.0下的System.Windows.Forms.dll, 否则会导致报错或者Unity闪退
using System.Data;
using OfficeOpenXml.DataValidation;
using Excel;
using System.IO;
using LitJson;
using System.Text;
using System.Text.RegularExpressions;
using System;
using System.CodeDom;
using System.Reflection;
using System.CodeDom.Compiler;

public class ExcelToJson : EditorWindow
{ 
   

    List<string> ExcelPath = new List<string>();
    string JsonPath;
    string CSharpPath;
    string JsonName;
    List<string> dataType = new List<string>();
    List<string> dataName = new List<string>();
    List<string[]> ExcelDateList = new List<string[]>();

    [UnityEditor.MenuItem("Tools/ExcelToJson")]
    static void ExceltoJson()
    { 
   
        ExcelToJson toJson = (ExcelToJson)EditorWindow.GetWindow(typeof(ExcelToJson), true, "ExcelToJson");
        toJson.Show();
    }

    private void OnGUI()
    { 
   
        Color oldColor = GUI.backgroundColor;

        GUI.backgroundColor = Color.red;
        if (GUILayout.Button("选择需要转换的excel文件"))
        { 
   
            GetAllExcelPath();
        }
        GUI.backgroundColor = oldColor;

        //Color color = new Color(201, 232, 255);
        //GUI.backgroundColor = Color.yellow;
        //if (GUILayout.Button("ExcelToJson"))
        //{ 
   
        // CreatJsonFile();
        //}
        //GUI.backgroundColor = oldColor;

        //GUI.backgroundColor = Color.gray;
        //if (GUILayout.Button("CreatCSharp"))
        //{ 
   
        // CreatCSharp();
        //}
        //GUI.backgroundColor = oldColor;

    }

    #region Excel文件处理
    void GetAllExcelPath()
    { 
   
        OpenFileDialog openFlie = new OpenFileDialog();
        openFlie.Title = "选择需要转换的excel文件";
        openFlie.InitialDirectory = @"F:\Cards\Tools\Excel";
        //openFlie.Filter = "(*.xlsm)|*.xlsm)";
        openFlie.Multiselect = true;    //可以多选
        ExcelPath.Clear();
        if (openFlie.ShowDialog() == DialogResult.OK)
        { 
   
            string[] strPath = openFlie.FileNames;
            for (int i = 0; i < strPath.Length; i++)
            { 
   
                ExcelPath.Add(strPath[i]);
                Debug.LogError(ExcelPath[i]);
                ReadExcel(strPath[i].Replace("\\", "/"));
            }
        }
    }

    /// <summary>
    /// 读取Excel
    /// </summary>
    /// <param name="path">excel路径</param>
    /// <param name="columnNum">列</param>
    /// <param name="rowNum">行</param>
    void ReadExcel(string path)
    { 
   
        FileStream stream = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.Read);
        IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
        DataSet data = excelReader.AsDataSet();
        dataName.Clear();
        dataType.Clear();
        //ExcelDateList.Clear();
        // 读取Excel的所有页签
        for (int i = 0; i < data.Tables.Count; i++)
        { 
   
            DataRowCollection dataRow = data.Tables[i].Rows;            // 每行
            DataColumnCollection dataColumn = data.Tables[i].Columns;   // 每列

            string tableName = data.Tables[i].TableName;
            JsonPath = UnityEngine.Application.dataPath + "/Editor/Json/";
            JsonName = tableName + ".json";
            JsonPath = JsonPath + JsonName;
            CSharpPath = UnityEngine.Application.dataPath + "/Scripts/ClassMgr/" + tableName + ".cs";

            for (int rowNum = 0; rowNum < data.Tables[i].Rows.Count; rowNum++)
            { 
   
                string[] table = new string[data.Tables[i].Columns.Count];
                for (int columnNum = 0; columnNum < data.Tables[i].Columns.Count; columnNum++)
                { 
   
                    if (rowNum == 0)  // 第一行的值:数据类型
                    { 
   
                        dataType.Add(data.Tables[i].Rows[0][columnNum].ToString());
                    }
                    else if (rowNum == 1)  // 第二行的值:数据名
                    { 
   
                        dataName.Add(data.Tables[i].Rows[1][columnNum].ToString());
                    }
                    else
                    { 
   
                        //Debug.Log(data.Tables[i].Rows[rowNum][columnNum].ToString() + "\n");
                        table[columnNum] = data.Tables[i].Rows[rowNum][columnNum].ToString();
                    }

                }
                if (rowNum > 1)
                { 
   
                    //将一行数据存入list
                    ExcelDateList.Add(table);
                }
            }
            
            CreatJsonFile();

            CreatCSharp(tableName);
        }
    }

    #endregion

    #region Excel转json
    void CreatJsonFile()
    { 
   
        if (File.Exists(JsonPath))
        { 
   
            File.Delete(JsonPath);
        }

        JsonData jsonDatas = new JsonData();
        jsonDatas.SetJsonType(JsonType.Array);

        for (int i = 0; i < ExcelDateList.Count; i++)
        { 
   
            JsonData jsonData = new JsonData();
            for (int j = 0; j < dataName.Count; j++)
            { 
   
                jsonData[dataName[j]] = ExcelDateList[i][j].ToString();
                //Debug.Log("第二轮输出:\n");
                //Debug.Log(ExcelDateList[i][j].ToString() + "\n");
            }
            jsonDatas.Add(jsonData);
        }
        string json = jsonDatas.ToJson();

        //防止中文乱码
        Regex reg = new Regex(@"(?i)\\[uU]([0-9a-f]{4})");
        StreamWriter writer = new StreamWriter(JsonPath, false, Encoding.GetEncoding("UTF-8"));
        writer.WriteLine(reg.Replace(json, delegate (Match m) { 
    return ((char)Convert.ToInt32(m.Groups[1].Value, 16)).ToString(); }));

        writer.Flush();
        writer.Close();

        System.Diagnostics.Process.Start("explorer.exe", JsonPath.Replace("/", "\\"));
    }
    #endregion

    #region 创建C#代码
    void CreatCSharp(string name)
    { 
   
        if (File.Exists(CSharpPath))
        { 
   
            File.Delete(CSharpPath);
        }
        //CodeTypeDeclaration 代码类型声明类
        CodeTypeDeclaration CSharpClass = new CodeTypeDeclaration(name);
        CSharpClass.IsClass = true;
        CSharpClass.TypeAttributes = TypeAttributes.Public;
        // 设置成员的自定义属性
        //CodeAttributeDeclaration代码属性声明
        //CodeTypeReference代码类型引用类
        //System.Serializable 给脚本打上[System.Serializable()]标签,将 成员变量 在Inspector中显示
        //CSharpClass.CustomAttributes.Add(new CodeAttributeDeclaration(new CodeTypeReference("System.Serializable")));
        for (int i = 0; i < dataName.Count; i++)
        { 
   
            // 创建字段
            //CodeMemberField 代码成员字段类 => (Type, string name)
            CodeMemberField member = new CodeMemberField(GetTypeForExcel(dataName[i], dataType[i]), dataName[i]);
            member.Attributes = MemberAttributes.Public;
            CSharpClass.Members.Add(member);
        }

        // 获取C#语言的实例
        CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp");
        //代码生成器选项类
        CodeGeneratorOptions options = new CodeGeneratorOptions();
        //设置支撑的样式
        options.BracingStyle = "C";
        //在成员之间插入空行
        options.BlankLinesBetweenMembers = true;

        StreamWriter writer = new StreamWriter(CSharpPath, false, Encoding.GetEncoding("UTF-8"));
        //生成最终代码
        provider.GenerateCodeFromType(CSharpClass, writer, options);

        writer.Flush();
        writer.Close();

        System.Diagnostics.Process.Start("explorer.exe", CSharpPath.Replace("/", "\\"));
    }

    Type GetTypeForExcel(string Name, string Type) { 
   
        if (Type == "int")
            return typeof(Int32);
        if (Type == "float")
            return typeof(Single);  //float关键字是System.Single的别名
        if (Type == "double")
            return typeof(Double);

        return typeof(String);
    }
    #endregion
}

Excel示例:
![在这里插入图片描述](https://img-blog.csdnimg.cn/41b7fe218c0b4ac9b407faef8b491a34.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBA5oiR5b6Q5Yek5bm0,size_20,color_FFFFFF,t_70,g_se,x_16
生成的C#脚本:
在这里插入图片描述

生成的json文件:
[{“ID”:“10001”,“Name”:“a”,“Explain”:“卡牌a”},{“ID”:“10002”,“Name”:“b”,“Explain”:“卡牌b”},{“ID”:“10003”,“Name”:“c”,“Explain”:“卡牌c”},{“ID”:“10004”,“Name”:“d”,“Explain”:“卡牌d”},{“ID”:“10005”,“Name”:“e”,“Explain”:“卡牌e”},{“ID”:“10006”,“Name”:“f”,“Explain”:“卡牌f”},{“ID”:“10007”,“Name”:“g”,“Explain”:“fas”},{“ID”:“10008”,“Name”:“h”,“Explain”:“gbfdsg”},{“ID”:“10009”,“Name”:“i”,“Explain”:“ewtg”},{“ID”:“10010”,“Name”:“j”,“Explain”:“sgs”},{“ID”:“10011”,“Name”:“k”,“Explain”:“mje”},{“ID”:“10012”,“Name”:“l”,“Explain”:“归属感”},{“ID”:“10013”,“Name”:“m”,“Explain”:“格式”},{“ID”:“10014”,“Name”:“n”,“Explain”:“搞完然后与”}]

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/139468.html原文链接:https://javaforall.net

(0)
上一篇 2022年5月29日 下午7:00
下一篇 2022年5月29日 下午7:00


相关推荐

  • css 两边到中间 渐变_CSS3 渐变

    css 两边到中间 渐变_CSS3 渐变CSS3 渐变渐变 gradients 可以在两个或多个指定的颜色之间显示平稳的过渡 兼容性 IE10 Chrome26 FireFox16 Safari6 1 Opera12 1 CSS3 线性渐变线性渐变属性 LinearGradie 是沿着一根轴线改变颜色 从起点到终点颜色进行顺序渐变 从一边拉向另一边 语法 background linear gradient direct

    2026年3月19日
    1
  • 手机自动进程管理软件_进程管理器下载

    手机自动进程管理软件_进程管理器下载大家好,我是小小明,今天要带大家做一款简易的网页版进程管理器,最终效果如下:目标只要求能查看内存使用何cpu使用率即可。基础模块技术测试读取进程信息首先,我们可以使用psutil读取服务端的进程使用情况(包括内存和CPU):importpsutiln=psutil.cpu_count()infos=[]forprocinpsutil.process_iter(attrs=[‘memory_info’,’name’,’pid’]):info=proc.in

    2025年10月23日
    4
  • OpenClaw Windows 10 家庭版安装教程:零基础40分钟跑通全流程

    OpenClaw Windows 10 家庭版安装教程:零基础40分钟跑通全流程

    2026年3月12日
    4
  • MySQL基础知识:存储过程 – Stored Procedure

    MySQL基础知识:存储过程 – Stored ProcedureMySQL存储过程(StoredProcedure)主要的知识点:分隔符(delimiter)变量(variable)参数(parameters)分隔符(DELIMITER)MySQL通过

    2022年7月2日
    27
  • 锐捷交换机基础配置命令

    锐捷交换机基础配置命令ip地址:ip地址就像你的名字,在你所在的地方管用。mac地址:就像你的身份证,在所有的地方都管用。enable—-进入特权模式config—-进入全局配置模式hostnameruijie2021—-更改设备名称vlan10—-创建vlan10(vlan-虚拟局域网)name123—-给vlan设置名称interfacevlan10—-进入vlan10ipaddress192.168.10.1255.255.255.0—

    2022年6月16日
    109
  • matlab拟合韦布尔分布,Matlab 三参数Weibull分布拟合求解

    matlab拟合韦布尔分布,Matlab 三参数Weibull分布拟合求解functiona b c wblthree x f x b a b x c b 1 exp x c a b a 尺度参数 b 形状参数 c 位置参数 disp 样本区间及最大值与最小值之比 x range min x max x max x min x alpha 0 05

    2026年3月18日
    2

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号