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)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • Xmn 与 NewSize 设置说明

    Xmn与 NewSize都是设置新生代的内存大小。经过测试,写在最后的一个参数起作用。下面是我的测试信息。第一次参数设置:    内存信息:S0C(13056)+S1C(13056)+EC(104960)=131072K=128M第二次参数设置:内存信息:S0C(20480)+S1C(20480)+EC(163840)=204800K=200M…

    2022年4月8日
    155
  • iocomp入门教程-以MFC中iplotx为例

    iocomp入门教程-以MFC中iplotx为例最近要做一个项目需要绘制曲线,为了节省时间,就选用了iocomp控件,可网上相关的教程极少,官方给的文档还是比较详尽,但缺少具体的前期准备步骤,在初次接触这个控件很容易蒙,所以我写下这篇,给入门者以便利。用到的材料:              iocomp激活成功教程版(目前常见的为V3和V4,两个版本按喜好选择吧~            

    2022年7月17日
    15
  • 灰色关联度分析(Grey Relation Analysis,GRA)原理详解[通俗易懂]

    灰色关联度分析(Grey Relation Analysis,GRA)原理详解[通俗易懂]释名灰色关联度分析(GreyRelationAnalysis,GRA),是一种多因素统计分析的方法。简单来讲,就是在一个灰色系统中,我们想要了解其中某个我们所关注的某个项目受其他的因素影响的相对强弱,再直白一点,就是说:我们假设以及知道某一个指标可能是与其他的某几个因素相关的,那么我们想知道这个指标与其他哪个因素相对来说更有关系,而哪个因素相对关系弱一点,依次类推,把这些因素排个序,得到一个…

    2022年7月17日
    16
  • 增长黑客目录_黑客手册书籍

    增长黑客目录_黑客手册书籍增长黑客手册——02增长黑客的数据分析方法趋势分析多维分解漏斗分析用户画像细查路径留存分析A/B测试增长黑客的能力市场营销技能搜索引擎优化(SearchEngineOptimization)营销自动化(MarketingAutomation)病毒传播(ViralRefferal)内容营销工程开发技能应用程序接口A/B测试数据分析技能数据统计数据分析数据的9款工具市场营销工具产品工程工具数据分析增长黑客的数据分析方法趋势分析通过对业务指标的检测研究用户规律,寻找增长点多维分解从多个维度进行拆

    2025年12月9日
    5
  • GROUP BY语句详解

    GROUP BY语句详解一、groupby的意思为分组汇总。使用了groupby后,要求Select出的结果字段都是可汇总的,否则就会出错。groupby有一个原则,就是select后面的所有列中,没有使用聚合函数的列,必须出现在groupby后面。比如,有:{学号,姓名,性别,年龄,成绩}字段这样写:SELECT学号,姓名,性别,年龄,sum(成绩)FROM学生表GROUPB…

    2022年5月26日
    41
  • linux与g++基本知识「建议收藏」

    linux与g++基本知识「建议收藏」基本知识gcc、g++、gdb区别yum、apt、rpm区别二进制包和源码包linux动态库和静态库cpp文件编译流程g++ 重要参数生成库文件生成静态库生成动态库GDB调试gcc、g++、gdb区别GCC:GNU Compiler Collection(GUN 编译器集合),它可以编译C、C++、JAV、Fortran、Pascal、Object-C、Ada等语言。gcc是GCC中的GUN C Compiler(C 编译器)g++是GCC中的GUN C++ Compiler(C++编译器)gd

    2022年8月9日
    5

发表回复

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

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