前言
这里我们需要理解动态生成CS文件的一些基础:https://blog.csdn.net/qq_37254346/article/details/103216761
怎样读取Excel表这里就不说了。
Excel表转CS文件
这是我们需要转的Excel表
这是转换后的CS文件
思路:首先读取到的Excel表第一行作为字段名,第三行是数据类型
[MenuItem("Component/Excel表转成C#类")]
public static void GenerateExcelToCsharp()
{
string[] excelPaths=FileTools.GetAllFiles(AssetData.ResPath, "xlsx"); //获取指定路径下的后缀名为xlsx的所有Excel文件
for (int i = 0; i < excelPaths.Length; i++)
{
string className = excelPaths[i].SubPath(); //截取路径获得文件名(这是我写的拓展方法)
className=className.Replace(".xlsx", ""); //去掉后缀得到类名
FileStream file = File.Open(excelPaths[i], FileMode.Open);
//使用c#读取Excel表的库
IExcelDataReader excelData = ExcelReaderFactory.CreateOpenXmlReader(file);
DataSet dataSet = excelData.AsDataSet();
//取第一张表
DataRowCollection rowCollection = dataSet.Tables[0].Rows;
CodeTypeDeclaration myClass = new CodeTypeDeclaration(className); //生成类
myClass.IsClass = true;
myClass.TypeAttributes = TypeAttributes.Public;
myClass.CustomAttributes.Add(new CodeAttributeDeclaration(new CodeTypeReference("System.Serializable"))); //添加序列化的特性
for (int j = 0; j < dataSet.Tables[0].Columns.Count; j++)
{
string type =rowCollection[2][j].ToString(); //这边我的Excel第三行填的是数据类型,这里把他读出来
string filed = rowCollection[0][j].ToString();//第一行字段名
CodeMemberField member = new CodeMemberField(GetTheType(type), filed); //生成字段
member.Attributes = MemberAttributes.Public;
myClass.Members.Add(member); //把生成的字段加入到生成的类中
}
CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp");
CodeGeneratorOptions options = new CodeGeneratorOptions(); //代码生成风格
options.BracingStyle = "C";
options.BlankLinesBetweenMembers = true;
string outputPath = AssetData.ExcelToCsharpOutputPath + @"\" + className + ".cs"; //指定文件的输出路径
using(StreamWriter sw=new StreamWriter(outputPath))
{
provider.GenerateCodeFromType(myClass, sw, options); //生成文件
}
}
}
/// <summary>
/// 获取类型
/// </summary>
/// <returns></returns>
private static Type GetTheType(string type)
{
switch (type)
{
case "string":
return typeof(String);
case "int":
return typeof(Int32);
case "float":
return typeof(Single);
case "long":
return typeof(Int64);
case "double":
return typeof(Double);
case "bigInteger":
return typeof(BigInteger);
default:
return typeof(String);
}
}