Unity编译器 《策划表编表工具》 Excel转Json自动生成解析c#代码

1.表格数据结构解释

2.Excel文件路径

3.C#代码与Json自动生成路径

点击下载依赖Dll程序集
4.下载好的依赖程序集放到Plugins中

5.Unity中整体结构

6.Tools 工具代码

using System;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using UnityEditor;
using UnityEngine;
using Excel;
using LitJson;
public class Tools : EditorWindow
{/// <summary>/// Execlw文件夹路径/// </summary>public static string ExeclPath =Application.dataPath.Replace("Assets","Excel");/// <summary>/// json路径/// </summary>public static string jsonPath = Application.dataPath+"/Json/";/// <summary>/// 创建的解析脚本CSharp路径/// </summary>public static string CSharpPath = Application.dataPath+"/CShop/";/// <summary>///  Execl To Json入口/// </summary>[MenuItem("Tools / Execl To Json and C#")]public static void StartExelToJson(){if (Directory.Exists(ExeclPath)){//文件路径DirectoryInfo directoryInfo = new DirectoryInfo(ExeclPath);//拿到所有的Exel路径FileInfo[] FilesAll = directoryInfo.GetFiles("*.xlsx");//循环序列化ExeclPath文件夹下所有表for (int i = 0; i < FilesAll.Length; i++){string ExcelTempPath = FilesAll[i].ToString();Debug.Log(" Excel绝对路径: " + ExcelTempPath);//构造Excel工具类ExcelUtility excel = new ExcelUtility(ExcelTempPath);excel.ConvertToJson(jsonPath, Encoding.GetEncoding("utf-8"), CSharpPath);//刷新本地资源AssetDatabase.Refresh();}}else{Debug.LogError("未找到路径");}}
}public class ExcelUtility
{/// <summary>/// 表格数据集合/// </summary>private DataSet mResultSet;private string TempexcelFile;List<string> dataName = new List<string>();List<string> dataType = new List<string>();/// <summary>/// 构造函数/// </summary>/// <param name="excelFile">Excel file.</param>public ExcelUtility(string excelFile){TempexcelFile = excelFile;using (FileStream mStream = File.Open(excelFile, FileMode.Open, FileAccess.Read)){IExcelDataReader mExcelReader = ExcelReaderFactory.CreateOpenXmlReader(mStream);mResultSet = mExcelReader.AsDataSet();}}/// <summary>/// 转换为Json/// string  int float  double  bool/// </summary>/// <param name="JsonPath">Json文件路径</param>/// <param name="Header">表头行数</param>public void ConvertToJson(string JsonPath, Encoding encoding, string CSharpPath){//判断Excel文件中是否存在数据表if (mResultSet.Tables.Count < 1)return;for (int x = 0; x < mResultSet.Tables.Count; x++){//默认读取第一个数据表DataTable mSheet = mResultSet.Tables[x];string outname = mSheet.TableName;if (outname.IndexOf('#') >= 0 && outname.LastIndexOf('#') != outname.IndexOf('#')){Debug.Log("无法导出名 " + outname + "  请确定#书写正确!");continue;}//判断数据表内是否存在数据if (mSheet.Rows.Count < 1)continue;//读取数据表行数和列数int rowCount = mSheet.Rows.Count;int colCount = mSheet.Columns.Count;//准备一个列表存储整个表的数据List<Dictionary<string, object>> table = new List<Dictionary<string, object>>();List<object> tempvaluestrList = null;string tempfield = null;string temptypestring = null;//读取数据for (int i = 3; i < rowCount; i++){//准备一个字典存储每一行的数据Dictionary<string, object> row = new Dictionary<string, object>();for (int j = 0; j < colCount; j++){//读取第1行数据作为表头字段string field = mSheet.Rows[1][j].ToString();field = field.Trim();if (field != ""){tempfield = field;if (!dataName.Contains(field)){dataName.Add(field);}}else if (tempfield != "" && field == ""){field = tempfield;}string typestring = mSheet.Rows[2][j].ToString();typestring = typestring.ToLower().Trim();if (typestring != ""){temptypestring = typestring;if (tempvaluestrList == null){tempvaluestrList = new List<object>();}else{tempvaluestrList.Clear();}dataType.Add(typestring);}else if (typestring == "" && temptypestring != ""){typestring = temptypestring;}string valuestr = mSheet.Rows[i][j].ToString();valuestr = valuestr.Trim();//Key-Value对应 按类型存放switch (typestring){case "int":if (valuestr != ""){row[field] = Convert.ToInt32(valuestr);}else{row[field] = 0;}break;case "float":if (valuestr != ""){row[field] = float.Parse(valuestr);}else{row[field] = 0;}break;case "double":if (valuestr != ""){row[field] = Convert.ToDouble(valuestr);}else{row[field] = 0;}break;case "bool":if (valuestr == "0" || valuestr == "fasle" || valuestr == ""){row[field] = false;}else{row[field] = true;}break;case "list<int>":tempvaluestrList.Add(valuestr);List<int> tempintList = new List<int>();for (int index = 0; index < tempvaluestrList.Count; index++){if (tempvaluestrList.Count > 0){if (tempvaluestrList[index].ToString() == ""){continue;}tempintList.Add(Convert.ToInt32(tempvaluestrList[index]));}}row[field] = tempintList;break;case "list<string>":tempvaluestrList.Add(valuestr);List<object> tempstringList = new List<object>();for (int index = 0; index < tempvaluestrList.Count; index++){if (tempvaluestrList.Count > 0){if (tempvaluestrList[index].ToString() == ""){continue;}tempstringList.Add(tempvaluestrList[index]);}}row[field] = tempstringList;break;default:row[field] = valuestr;break;}}//添加到表数据中table.Add(row);}//生成Json字符串string json = JsonMapper.ToJson(table);//修复中文乱码Regex reg = new Regex(@"(?i)\\[uU]([0-9a-f]{4})");json = reg.Replace(json,delegate(Match m) { return ((char)Convert.ToInt32(m.Groups[1].Value, 16)).ToString(); });string JsonFilePath = JsonPath+ Path.GetFileNameWithoutExtension(TempexcelFile) + ".json";//写入文件using (FileStream fileStream = new FileStream(JsonFilePath, FileMode.Create, FileAccess.Write)){using (TextWriter textWriter = new StreamWriter(fileStream, encoding)){textWriter.Write(json);}}CreatCSharp(Path.GetFileNameWithoutExtension(TempexcelFile) + "Array", CSharpPath);dataName.Clear();dataType.Clear();}}#region 创建C#代码void CreatCSharp(string name, string CSharpPath){CSharpPath += name + ".cs";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);}//生成解析函数CodeMemberMethod method1 = new CodeMemberMethod();method1.Attributes = MemberAttributes.Public | MemberAttributes.Static | MemberAttributes.Final;method1.Name = "LoadJson";method1.ReturnType = new CodeTypeReference("System.Collections.Generic.List<" + name + ">");//method1.Parameters.Add( new CodeParameterDeclarationExpression("System.String", "text") );//method1.Statements.Add( new CodeMethodReturnStatement( new CodeArgumentReferenceExpression("text") ) );method1.Statements.Add(new CodeVariableDeclarationStatement(typeof(string), "jsonPath",new CodePrimitiveExpression("/Json/" + name.Replace("Array","") + ".json")));method1.Statements.Add(new CodeArgumentReferenceExpression("System.Collections.Generic.List<" + name +"> jsonArray=LitJson.JsonMapper.ToObject<System.Collections.Generic.List<" +name +">>(System.IO.File.ReadAllText(UnityEngine.Application.dataPath+jsonPath,System.Text.Encoding.UTF8))"));method1.Statements.Add(new CodeMethodReturnStatement(new CodeArgumentReferenceExpression("jsonArray")));CSharpClass.Members.Add(method1);// 获取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();}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);if (Type == "bool")return typeof(Boolean);if (Type == "list<int>")return typeof(List<Int32>);if (Type == "list<string>")return typeof(List<String>);return typeof(String);}#endregion
}

Unity编译器 《策划表编表工具》 Excel转Json自动生成解析c#代码相关推荐

  1. quicktype游戏java程序_使用QuickType工具从json自动生成类型声明代码

    一.QuickType 工具功能简介 QuickType 是一款可以根据 json 文本生成指定语言(如 Type Script,C++,,Java,C#,Go 等)类型声明代码的工具. 例如我们在写 ...

  2. 在Unity上编写一个小工具--Excel导出Json

    这是个Excel导出Json的工具类,需要放进Editor文件夹里,之后就可以在菜单上点击导出了 这个工具运行需要一个插件----NPOI,这个是用来读取excel文件的,这个插件的dll文件可以去网 ...

  3. 懒人小工具1:winform自动生成Model,Insert,Select,Delete以及导出Excel的方法

       懒人小工具2:T4自动生成Model,Insert,Select,Delete以及导出Excel的方法    github地址:https://github.com/Jimmey-Jiang/J ...

  4. 使用xorm工具,根据数据库自动生成 go 代码

    引入 使用 golang 操作数据库的同学都会遇到一个问题 -- 根据数据表结构创建对应的 struct 模型.因为 golang 的使用首字母控制可见范围,我们经常要设计 struct 字段名和数据 ...

  5. 如何设置Oracle工作表有提示,excel表格中自动数据提醒-excel工作表中如何自动跳出提醒框...

    excel表格怎么设置到期日前自动提醒功能 菜单项〉工具>选项.在图中选择.在弹出的对话框中把"记忆式键入"前面的对勾去掉行了. 详见图示. 在Excel表格里面怎样设置&q ...

  6. GreenDao 工具类 --- 使用 Json 快速生成 Bean、表及其结构,炒鸡快!

    作者:林冠宏 / 指尖下的幽灵 掘金:https://juejin.im/user/587f0dfe128fe100570ce2d8 博客:http://www.cnblogs.com/linguan ...

  7. EXCEL 文档自动生成目录

    excel 文档一般都有很多sheet, 需要在sheet1 上面做一个目录,方便快速打开对应的sheet,但是excel没有自动生成的功能,研究了一下excel的开发工具,用vb命令来实现这个功能. ...

  8. oracle导出建表主键,oracle主键自动生成 配合hibernate的生成策略详解

    hibernate配合oracle自动生成主键策略有两种方法: A)设置ID的增长策略是sequence,同时指定sequence的名字,最好每个表建一个sequence,此种做法就如同MS-SQL, ...

  9. postman生成python代码_别再用手敲了,这个工具可以自动生成python爬虫代码

    我们在写爬虫代码时,常常需要各种分析调试,而且每次直接用代码调试都很麻烦 所以今天给大家分享一个工具,不仅能方便模拟发送各种http请求,还能轻松调试,最重要的是,可以将调试最终结果自动转换成爬虫代码 ...

最新文章

  1. 配置hadoop集群一
  2. Android 中View的绘制机制源代码分析 三
  3. Ubuntu安装Rstudio
  4. 亚马逊AWS:正确设置FTP
  5. 使用 TreeSet 生成数组
  6. php nl2br() 函数
  7. sql server管理学习提纲
  8. 互信息的数学解释以及matlab编程
  9. 为什么需要消息队列MQ
  10. win10安装opcenum_Win10提示Windows无法安装到GPT分区形式磁盘
  11. flutter 禁止冒泡_【Flutter】Switch开关组件
  12. r如何查询mysql中的数据类型_MySQL-mysql中的数据类型
  13. 利用组策略管理器映射网络驱动器的方法
  14. 吐槽Javascript系列三:数组的陷阱
  15. 构建大型 Mobx 应用的几个建议
  16. win7电脑网站服务器,Win7系统
  17. 专题:固体力学中应力与应变分析详解(4.应力张量的转换)
  18. 2018年上半年阅读总结(系统架构师)
  19. UWP 禁止Pivot swip 手势
  20. 波束赋形技术lms算法在matlab仿真,自适应波束成形算法LMS、RLS、VSSLMS分解

热门文章

  1. 【无标题】tensorflow hub 预训练模型库
  2. smi-s java_SMI-S协议简介
  3. springboot 大文件分片上传、断点续传和秒传
  4. 中国装饰蜡烛市场深度研究分析报告
  5. Google 的十大信条
  6. SSL协议的分析及实现
  7. [笔记分享] [Camera] 各种相机种类及区别
  8. 使用vtwinfx插件时fcpx意外退出_FCPX插件 60个自媒体文字标题字幕条Motion Graphics Pack...
  9. 圣战之系谱 恋爱系统详解
  10. 模拟电路设计:理论的神话与残酷的现实