一个简单的Excel导表工具,可以用来热更数据配置

工具使用:

  1. 执行菜单 SDGSupporter/Excel/1.Excel2Cs 生成c#脚本。
  2. 等待C#类编译完成
  3. 执行菜单 SDGSupporter/Excel/2.Excel2Bytes 生成XmI临时文件,生成bytes二进制表格数据,删除xml临时文件。
  4. 运行场景SampleScene.unity Console面板打印表格内容。

工具代码:

Assets\Editor\Excel2CsBytesTool.cs 文件夹路径可配置在这里Assets\Scripts\BaseTable.cs Excel配置时支持的类型数组

源Excel文件夹:

ExcelData

生成的C#类:

eg: Assets \Scripts \DataTable \weapon.cs

生成的bytes文件:

eg: Resources \DataTable \weapon.bytes

首先准备一个Excel表 填入数据,注意需要放在Edior目录下

然后编写Excel2CsBytesTool.cs脚本

附上完整代码:

using System.IO;
using Excel;
using System.Data;
using UnityEditor;
using UnityEngine;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using Table;
using System;
using System.Xml;
using System.Xml.Serialization;
using System.Runtime.Serialization.Formatters.Binary;/// <summary>
/// Excel生成bytes和cs工具
/// </summary>
public class Excel2CsBytesTool
{static string ExcelDataPath = Application.dataPath + "/../ExcelData";//源Excel文件夹,xlsx格式static string BytesDataPath = Application.dataPath + "/Resources/DataTable";//生成的bytes文件夹static string CsClassPath = Application.dataPath + "/Scripts/DataTable";//生成的c#脚本文件夹static string XmlDataPath = ExcelDataPath + "/tempXmlData";//生成的xml(临时)文件夹..static string AllCsHead = "all";//序列化结构体的数组类.类名前缀static char ArrayTypeSplitChar = '#';//数组类型值拆分符: int[] 1#2#34 string[] 你好#再见 bool[] true#false ...static bool IsDeleteXmlInFinish = true;//生成bytes后是否删除中间文件xml[MenuItem("SDGSupporter/Excel/Excel2Cs")]static void Excel2Cs(){Init();Excel2CsOrXml(true);}[MenuItem("SDGSupporter/Excel/Excel2Bytes")]static void Excel2Xml2Bytes(){Init();//生成中间文件xmlExcel2CsOrXml(false);//生成bytesWriteBytes();}static void Init(){if (!Directory.Exists(CsClassPath)){Directory.CreateDirectory(CsClassPath);}if (!Directory.Exists(XmlDataPath)){Directory.CreateDirectory(XmlDataPath);}if (!Directory.Exists(BytesDataPath)){Directory.CreateDirectory(BytesDataPath);}}static void WriteCs(string className, string[] names, string[] types, string[] descs){try{StringBuilder stringBuilder = new StringBuilder();stringBuilder.AppendLine("using System;");stringBuilder.AppendLine("using System.Collections.Generic;");stringBuilder.AppendLine("using System.IO;");stringBuilder.AppendLine("using System.Runtime.Serialization.Formatters.Binary;");stringBuilder.AppendLine("using System.Xml.Serialization;");stringBuilder.Append("\n");stringBuilder.AppendLine("namespace Table");stringBuilder.AppendLine("{");stringBuilder.AppendLine("    [Serializable]");stringBuilder.AppendLine("    public class " + className);stringBuilder.AppendLine("    {");for (int i = 0; i < names.Length; i++){stringBuilder.AppendLine("        /// <summary>");stringBuilder.AppendLine("        /// " + descs[i]);stringBuilder.AppendLine("        /// </summary>");stringBuilder.AppendLine("        [XmlAttribute(\"" + names[i] + "\")]");string type = types[i];if (type.Contains("[]")){//type = type.Replace("[]", "");//stringBuilder.AppendLine("        public List<" + type + "> " + names[i] + ";");//可选代码://用_name字段去反序列化,name取_name.item的值,直接返回list<type>。//因为xml每行可能有多个数组字段,这样就多了一层变量item,所以访问的时候需要.item才能取到list<type>//因此用额外的一个变量直接返回List<type>。type = type.Replace("[]", "");stringBuilder.AppendLine("        public List<" + type + "> " + names[i] + "");stringBuilder.AppendLine("        {");stringBuilder.AppendLine("            get");stringBuilder.AppendLine("            {");stringBuilder.AppendLine("                if (_" + names[i] + " != null)");stringBuilder.AppendLine("                {");stringBuilder.AppendLine("                    return _" + names[i] + ".item;");stringBuilder.AppendLine("                }");stringBuilder.AppendLine("                return null;");stringBuilder.AppendLine("            }");stringBuilder.AppendLine("        }");stringBuilder.AppendLine("        [XmlElementAttribute(\"" + names[i] + "\")]");stringBuilder.AppendLine("        public " + type + "Array _" + names[i] + ";");}else{stringBuilder.AppendLine("        public " + type + " " + names[i] + ";");}stringBuilder.Append("\n");}stringBuilder.AppendLine("        public static List<" + className + "> LoadBytes()");stringBuilder.AppendLine("        {");stringBuilder.AppendLine("            string bytesPath = \"" + BytesDataPath + "/" + className + ".bytes\";");stringBuilder.AppendLine("            if (!File.Exists(bytesPath))");stringBuilder.AppendLine("                return null;");stringBuilder.AppendLine("            using (FileStream stream = new FileStream(bytesPath, FileMode.Open))");stringBuilder.AppendLine("            {");stringBuilder.AppendLine("                BinaryFormatter binaryFormatter = new BinaryFormatter();");stringBuilder.AppendLine("                all" + className + " table = binaryFormatter.Deserialize(stream) as all" + className + ";");stringBuilder.AppendLine("                return table." + className + "s;");stringBuilder.AppendLine("            }");stringBuilder.AppendLine("        }");stringBuilder.AppendLine("    }");stringBuilder.Append("\n");stringBuilder.AppendLine("    [Serializable]");stringBuilder.AppendLine("    public class " + AllCsHead + className);stringBuilder.AppendLine("    {");stringBuilder.AppendLine("        public List<" + className + "> " + className + "s;");stringBuilder.AppendLine("    }");stringBuilder.AppendLine("}");string csPath = CsClassPath + "/" + className + ".cs";if (File.Exists(csPath)){File.Delete(csPath);}using (StreamWriter sw = new StreamWriter(csPath)){sw.Write(stringBuilder);Debug.Log("生成:" + csPath);}}catch (System.Exception e){Debug.LogError("写入CS失败:" + e.Message);throw;}}static void WriteXml(string className, string[] names, string[] types, List<string[]> datasList){try{StringBuilder stringBuilder = new StringBuilder();stringBuilder.AppendLine("<?xml version=\"1.0\" encoding=\"utf-8\"?>");stringBuilder.AppendLine("<" + AllCsHead + className + ">");stringBuilder.AppendLine("<" + className + "s>");for (int d = 0; d < datasList.Count; d++){stringBuilder.Append("\t<" + className + " ");//单行数据string[] datas = datasList[d];//填充属性节点for (int c = 0; c < datas.Length; c++){string type = types[c];if (!type.Contains("[]")){string name = names[c];string value = datas[c];stringBuilder.Append(name + "=\"" + value + "\"" + (c == datas.Length - 1 ? "" : " "));}}stringBuilder.Append(">\n");//填充子元素节点(数组类型字段)for (int c = 0; c < datas.Length; c++){string type = types[c];if (type.Contains("[]")){string name = names[c];string value = datas[c];string[] values = value.Split(ArrayTypeSplitChar);stringBuilder.AppendLine("\t\t<" + name + ">");for (int v = 0; v < values.Length; v++){stringBuilder.AppendLine("\t\t\t<item>" + values[v] + "</item>");}stringBuilder.AppendLine("\t\t</" + name + ">");}}stringBuilder.AppendLine("\t</" + className + ">");}stringBuilder.AppendLine("</" + className + "s>");stringBuilder.AppendLine("</" + AllCsHead + className + ">");string xmlPath = XmlDataPath + "/" + className + ".xml";if (File.Exists(xmlPath)){File.Delete(xmlPath);}using (StreamWriter sw = new StreamWriter(xmlPath)){sw.Write(stringBuilder);Debug.Log("生成文件:" + xmlPath);}}catch (System.Exception e){Debug.LogError("写入Xml失败:" + e.Message);}}static void Excel2CsOrXml(bool isCs){string[] excelPaths = Directory.GetFiles(ExcelDataPath, "*.xlsx");for (int e = 0; e < excelPaths.Length; e++){//0.读Excelstring className;//类型名string[] names;//字段名string[] types;//字段类型string[] descs;//字段描述List<string[]> datasList;//数据try{string excelPath = excelPaths[e];//excel路径  className = Path.GetFileNameWithoutExtension(excelPath).ToLower();FileStream fileStream = File.Open(excelPath, FileMode.Open, FileAccess.Read);IExcelDataReader excelDataReader = ExcelReaderFactory.CreateOpenXmlReader(fileStream);// 表格数据全部读取到result里DataSet result = excelDataReader.AsDataSet();// 获取表格列数int columns = result.Tables[0].Columns.Count;// 获取表格行数int rows = result.Tables[0].Rows.Count;// 根据行列依次读取表格中的每个数据names = new string[columns];types = new string[columns];descs = new string[columns];datasList = new List<string[]>();for (int r = 0; r < rows; r++){string[] curRowData = new string[columns];for (int c = 0; c < columns; c++){//解析:获取第一个表格中指定行指定列的数据string value = result.Tables[0].Rows[r][c].ToString();//清除前两行的变量名、变量类型 首尾空格if (r < 2){value = value.TrimStart(' ').TrimEnd(' ');}curRowData[c] = value;}//解析:第一行类变量名if (r == 0){names = curRowData;}//解析:第二行类变量类型else if (r == 1){types = curRowData;}//解析:第三行类变量描述else if (r == 2){descs = curRowData;}//解析:第三行开始是数据else{datasList.Add(curRowData);}}}catch (System.Exception exc){Debug.LogError("请关闭Excel:" + exc.Message);return;}if (isCs){//写CsWriteCs(className, names, types, descs);}else{//写XmlWriteXml(className, names, types, datasList);}}AssetDatabase.Refresh();}static void WriteBytes(){string csAssemblyPath = Application.dataPath + "/../Library/ScriptAssemblies/Assembly-CSharp.dll";Assembly assembly = Assembly.LoadFile(csAssemblyPath);if (assembly != null){Type[] types = assembly.GetTypes();for (int i = 0; i < types.Length; i++){Type type = types[i];if (type.Namespace == "Table" && type.Name.Contains(AllCsHead)){string className = type.Name.Replace(AllCsHead, "");//读取xml数据string xmlPath = XmlDataPath + "/" + className + ".xml";if (!File.Exists(xmlPath)){Debug.LogError("Xml文件读取失败:" + xmlPath);continue;}object table;using (Stream reader = new FileStream(xmlPath, FileMode.Open)){//读取xml实例化table: all+classname//object table = assembly.CreateInstance("Table." + type.Name);XmlSerializer xmlSerializer = new XmlSerializer(type);table = xmlSerializer.Deserialize(reader);}//obj序列化二进制string bytesPath = BytesDataPath + "/" + className + ".bytes";if (File.Exists(bytesPath)){File.Delete(bytesPath);}using (FileStream fileStream = new FileStream(bytesPath, FileMode.Create)){BinaryFormatter binaryFormatter = new BinaryFormatter();binaryFormatter.Serialize(fileStream, table);Debug.Log("生成:" + bytesPath);}if (IsDeleteXmlInFinish){File.Delete(xmlPath);Debug.Log("删除:" + bytesPath);}}}}if (IsDeleteXmlInFinish){Directory.Delete(XmlDataPath);Debug.Log("删除:" + XmlDataPath);}}
}

接着是自定义的数据配置类:

using System;
using System.Collections.Generic;
using System.Xml.Serialization;/// <summary>
/// Excel2CsBytesTool
/// Excel可以配置的数组类型:string[] int[] bool[] 
/// 可自行扩展
/// </summary>
namespace Table
{[System.SerializableAttribute()][System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]public class stringArray{[System.Xml.Serialization.XmlElementAttribute("item")]public List<string> item { get; set; }}[System.SerializableAttribute()][System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]public class intArray{[System.Xml.Serialization.XmlElementAttribute("item")]public List<int> item { get; set; }}[System.SerializableAttribute()][System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]public class boolArray{[System.Xml.Serialization.XmlElementAttribute("item")]public List<bool> item { get; set; }}
}

然后就可以在Unity菜单界面看到我们的编辑器工具了

先点击Execl2Cs生成相应的C#脚本(会先清除原先的) 其后点击2Bytes,将数据序列化成二进制

等待执行完成后点击运行。便可以看到我们的consloe界面出现我们在Excel表中配置的数据。

Excel导表工具就完成了。可以自行扩展。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若转载,请注明出处:http://www.pswp.cn/web/91119.shtml
繁体地址,请注明出处:http://hk.pswp.cn/web/91119.shtml
英文地址,请注明出处:http://en.pswp.cn/web/91119.shtml

如若内容造成侵权/违法违规/事实不符,请联系英文站点网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

【数据结构与算法】力扣 415. 字符串相加

题目描述 415. 字符串相加 给定两个字符串形式的非负整数 num1 和num2 &#xff0c;计算它们的和并同样以字符串形式返回。 你不能使用任何內建的用于处理大整数的库&#xff08;比如 BigInteger&#xff09;&#xff0c; 也不能直接将输入的字符串转换为整数形式。 示例 1…

进阶向:Manus AI与多语言手写识别

Manus AI与多语言手写识别:从零开始理解 手写识别技术作为人工智能领域的重要应用之一,近年来在智能设备、教育、金融等行业得到了广泛运用。根据市场调研机构IDC的数据显示,2022年全球手写识别市场规模已达到45亿美元,预计到2025年将突破70亿美元。其中,多语言手写识别技…

Javaweb————HTTP请求头属性讲解

❤️❤️❤️❤️❤️❤️❤️❤️❤️❤️❤️前面我们已经说过http请求分为三部分&#xff0c;请求行&#xff0c;请求头和请求体 请求头包含若干个属性&#xff1a;格式为属性名&#xff1a;属性值&#xff0c;这篇文章我们就来介绍一下http请求头中一些常见属性的含义 我们…

9.c语言常用算法

查找顺序查找&#xff08;线性查找&#xff09;算法思想&#xff1a;从数组的第一个元素开始&#xff0c;逐个与目标值进行比较&#xff0c;直到找到目标值或查找完整个数组。时间复杂度&#xff1a;最好情况&#xff1a;O(1)&#xff08;目标在第一个位置&#xff09;最坏情况…

AI小智源码分析——音频部分(一)

一、源码跳转这里采用了函数重载来进行代码复用&#xff0c;当需要对I2S接口的数据进行配置&#xff0c;比如左右音道切换&#xff0c;可以使用第二个构造函数&#xff0c;这里小智使用的是第一个构造函数&#xff0c;即只传递I2S相关的引脚参数&#xff08;不带slot mask&…

【GNSS原理】【LAMBDA】Chapter.12 GNSS定位算法——模糊度固定LAMBDA算法[2025年7月]

Chapter.12 GNSS定位算法——模糊度固定LAMBDA算法 作者&#xff1a;齐花Guyc(CAUC) 文章目录Chapter.12 GNSS定位算法——模糊度固定LAMBDA算法一.整周模糊度理论1.LAMBDA算法干了一件什么事情&#xff1f;2.LAMBDA算法步骤&#xff08;1&#xff09;去相关&#xff08;Z变换…

计算机毕业设计java在线二手系统的设计与实现 基于Java的在线二手交易平台开发 Java技术驱动的二手物品管理系统

计算机毕业设计java在线二手系统的设计与实现z2n189&#xff08;配套有源码 程序 mysql数据库 论文&#xff09; 本套源码可以在文本联xi,先看具体系统功能演示视频领取&#xff0c;可分享源码参考。随着互联网技术的飞速发展&#xff0c;二手交易市场也逐渐从传统的线下模式转…

如何进行项目复盘?核心要点分析

进行项目复盘需要明确复盘目标、确定复盘参与人员、选择合适的复盘方法、梳理项目过程与关键节点、分析成功与失败的原因、总结经验教训并制定改进计划。其中&#xff0c;选择合适的复盘方法尤其关键&#xff0c;常见的复盘方法包括鱼骨图分析法、SWOT分析法、PDCA循环法&#…

LeetCode 923.多重三数之和

给定一个整数数组 arr &#xff0c;以及一个整数 target 作为目标值&#xff0c;返回满足 i < j < k 且 arr[i] arr[j] arr[k] target 的元组 i, j, k 的数量。 由于结果会非常大&#xff0c;请返回 109 7 的模。 示例 1&#xff1a; 输入&#xff1a;arr [1,1,2,2,…

.Net日志系统Logging-五

日志概念 日志级别 NET (Microsoft.Extensions.Logging) 中定义的 6 个标准日志级别&#xff0c;按严重性从低到高排列&#xff1a; 日志级别数值描述典型使用场景Trace0最详细的信息&#xff0c;包含敏感数据&#xff08;如请求体、密码哈希等&#xff09;。仅在开发或深度故…

中国贸促会融媒体中心出海活动负责人、出海星球创始人莅临绿算技术

近日&#xff0c;中国贸促会融媒体中心出海活动负责人、出海星球创始人王思诺一行莅临广东省绿算技术有限公司&#xff0c;深入考察其核心技术产品与全球化布局。双方围绕绿算技术全栈产品体系、创新出海模式及生态共建展开深度对话。绿算技术作为国内智算基础设施领域的领军企…

【算法专题训练】06、数组双指针

1、数组 数组是由相同类型的元素组成的数据集合&#xff0c;并且占据一块连续的内存&#xff0c;按照顺序存储数据。 1.1、数组的特性&#xff1a; 数组元素通过下标获取数据数组对象初始化时&#xff0c;需要先指定数组容量大小&#xff0c;并根据容量大小分配内存。缺点&…

操作系统-lecture2(操作系统结构)

回顾下lecture1 swap区域不可以马上执行&#xff0c;即虚拟内存的数据和指令不可以被执行&#xff0c;得交换回到内存区域 操作系统的服务 主要提供两种服务 面向普通用户&#xff1a;user interface面向程序员&#xff1a;应用级程序代码 为用户 为用户提供了操作包括但不…

内网服务器实现从公网穿透

从6月份tplink的ddns失效之后&#xff0c;对于部分在内网运行的服务器&#xff0c;从公网访问就收到了部分影响。有好几个朋友找来&#xff0c;寻求帮助&#xff0c;看看怎么恢复原来的机制&#xff0c;可以从公网互联网访问内网服务器。方案一&#xff1a;如果有动态公网的客户…

vcs-编译+仿真+dump波形【IMP】

VCS仿真分为两步式(编译/compilation仿真/simulation)和三步式(分析/analysis细化/elaborationsimulation/仿真);注2:analysis/分析是三步式flow中仿真design的第一步&#xff0c;在此阶段将使用vhdlan或vlogan分析VHDL、Verilog、SystemVerilog和OpenVera文件。下面的部分包括…

程序代码篇---python向http界面发送数据

在 Python 中向 HTTP 界面发送数据&#xff0c;本质上是模拟用户在网页上填写表单、点击提交按钮的过程。这在自动化测试、数据上报、接口调用等场景中非常常用。下面用通俗易懂的方式介绍具体方法、实例代码和解析。核心原理网页上的数据发送&#xff08;比如提交表单&#xf…

mybatis-plus由mysql改成达梦数据库

前置条件: 达梦数据库设置了大小写敏感,我比较菜,改不动!先这么凑合着用吧; 因为设置了大小写敏感,所以所有的sql语句都要加 引号; 这样是会报错的: SELECT remark,createDept,createBy,createTime,updateBy,updateTime FROM sys_oss_config这样才可以 SELECT "create_…

设计模式:外观模式 Facade

目录前言问题解决方案结构代码前言 外观是一种结构型设计模式&#xff0c;能为程序库、框架或其他复杂类提供一个简单的接口。 问题 假设你必须在代码中使用某个复杂的库或框架中的众多对象。正常情况下&#xff0c; 你需要负责所有对象的初始化工作、 管理其依赖关系并按正确…

【数据结构初阶】--二叉树(四)

&#x1f525;个人主页&#xff1a;草莓熊Lotso &#x1f3ac;作者简介&#xff1a;C研发方向学习者 &#x1f4d6;个人专栏&#xff1a; 《C语言》 《数据结构与算法》《C语言刷题集》《Leetcode刷题指南》 ⭐️人生格言&#xff1a;生活是默默的坚持&#xff0c;毅力是永久的…

三、平面度检测-差值法

方法一: dev_get_window (WindowHandle) *读取3通道彩色融合图 read_image (Image, ./XYZ彩色融合图.tiff) *拆分3个通道 decompose3 (Image, x, y, z) *将3个通道图像转换为3D模型 xyz_to_object_model_3d (x,y, z, ObjectModel3D) *显示动态3D模型 threshold (z, Regions,…