Unity数据持久化 之 一个通过2进制读取Excel并存储的轮子(2) (*****生成数据结构类的方式特别有趣****)

本文仅作笔记学习和分享,不用做任何商业用途

本文包括但不限于unity官方手册,unity唐老狮等教程知识,如有不足还请斧正​​

Unity数据持久化 之 一个通过2进制读取Excel并存储的轮子(1)-CSDN博客

本节内容

实现目标

通过已经得到的Excel表格数据,生成对应类对象(不赋值),一张表就是一个对象,其中包含了如下的字段

就像这样子

实现思路

上节已经获取了一个个单元格,那直接利用其中的字段进行字符串拼接

然后把这个字符串通过文件处理存到一个脚本文件之中就行了,自然就识别成了类对象了

实现过程

生成数据结构类的脚本的路径

cs 复制代码
  //数据结构类脚本存储
  private static string Data_Class_Path = Application.dataPath + "/Scripts/ExcelData/DataClass/";

获得表中的字段名和字段类型

cs 复制代码
   //生成数据结构类的方法
   private static void GenerateExcelDataClass(DataTable dataTable)
   {
       GetVariableNameRow(dataTable);
       GetVariableDataTypeRow(dataTable);


   }
   //获取表中行字段名字的方法
   private static DataRow GetVariableNameRow(DataTable dataTable)
   { 
   return dataTable.Rows[0];   //索引可修改
   }
   //获取表中行字段数据类型的方法
   private static DataRow GetVariableDataTypeRow(DataTable dataTable)
   {
       return dataTable.Rows[1];//索引可修改
   }

确认或创建存储数据结构脚本的路径

cs 复制代码
  DataRow dataRowName= GetVariableNameRow(dataTable);
  DataRow dataRowType= GetVariableDataTypeRow(dataTable);
   //判断存储该脚本的路径是否为空
   if(!Directory.Exists(Data_Class_Path))
       Directory.CreateDirectory(Data_Class_Path);

狠狠拼接字符串

cs 复制代码
  for (int i = 0; i < dataTable.Columns.Count; i++)
  {
      str += "  public" + dataRowType[0].ToString() + " " + dataRowName[i].ToString() + ";" + "\n";
  }

  str += "}";

存入先前的路径中,生成脚本

Windows.File-WriteAllBytes - Unity 脚本 API

cs 复制代码
 ///dataTable.TableName.ToString() =类名,".cs"=后缀名,str=内容
 File.WriteAllText(Data_Class_Path+dataTable.TableName.ToString()+".cs", str);

最终结果

cs 复制代码
using Excel;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.IO;
using UnityEditor;
using UnityEngine;

public class ExcelTools 
{
    // 表格文件夹的路径
    private static string Excel_Path = Application.dataPath + "/Excel/";

    //数据结构类脚本存储
    private static string Data_Class_Path = Application.dataPath + "/Scripts/ExcelData/DataClass/";

    // 生成和读取表格的方法
    [MenuItem("Tool/GenerateExcel")]
    private static void GenerateExcelInfo()
    {
        // 创建或返回表格文件夹的路径
        DirectoryInfo directoryInfo = Directory.CreateDirectory(Excel_Path);
        // 获取文件夹中的所有文件
        FileInfo[] fileInfo = directoryInfo.GetFiles();
        // 数据表集合
        DataTableCollection dataTableCollection;

        for (int i = 0; i < fileInfo.Length; i++)
        {
            // 筛选出扩展名为 .xlsx 或 .xls 的文件
            if (fileInfo[i].Extension != ".xlsx" && fileInfo[i].Extension != ".xls")
                continue;

            // 打开文件流读取表格
            using (FileStream fs = fileInfo[i].Open(FileMode.Open, FileAccess.Read))
            {
                // 使用 IExcelDataReader 读取表格数据
                IExcelDataReader excelDataReader = ExcelReaderFactory.CreateOpenXmlReader(fs);
                dataTableCollection = excelDataReader.AsDataSet().Tables; // 转换为数据表集合
                fs.Close();
            }

            // 输出每个工作表的名称
            foreach (DataTable temp in dataTableCollection)
            {
                Debug.Log(temp.TableName);

                //生成数据结构类
                GenerateExcelDataClass(temp);
            }
           

        }
    }

    //生成数据结构类的方法
    private static void GenerateExcelDataClass(DataTable dataTable)
    {
       DataRow dataRowName= GetVariableNameRow(dataTable);
       DataRow dataRowType= GetVariableDataTypeRow(dataTable);
        //判断存储该脚本的路径是否为空
        if(!Directory.Exists(Data_Class_Path))
            Directory.CreateDirectory(Data_Class_Path);

        string str = "public class " + dataTable.TableName.ToString()+"\n{\n";

        for (int i = 0; i < dataTable.Columns.Count; i++)
        {
            str += "  public " + dataRowType[0].ToString() + " " + dataRowName[i].ToString() + ";" + "\n";
        }

        str += "}";

        ///dataTable.TableName.ToString() =类名,".cs"=后缀名,str=内容
        File.WriteAllText(Data_Class_Path+dataTable.TableName.ToString()+".cs", str);

    }
    //获取表中行字段名字的方法
    private static DataRow GetVariableNameRow(DataTable dataTable)
    { 
    return dataTable.Rows[0];   //索引可修改
    }
    //获取表中行字段数据类型的方法
    private static DataRow GetVariableDataTypeRow(DataTable dataTable)
    {
        return dataTable.Rows[1];//索引可修改
    }
}
相关推荐
asdzx672 分钟前
使用 Python 精准操控 Word 字体:获取与替换方案
python·c#·word
逝水无殇2 小时前
C# 特性详解
开发语言·后端·c#
LongtengGensSupreme3 小时前
C#图像内存高速拷贝:使用Marshal.AllocHGlobal与ArrayPool实现内存拷贝的几个方法
开发语言·数码相机·c#
chatexcel3 小时前
不用写 SQL,如何用AI直连数据库生成可刷新的数据看板?ChatExcel的一种实践
大数据·数据库·人工智能·sql·数据分析·excel
玖玥拾4 小时前
Unity 3D 基础(一)Unity基础架构、物理系统、视觉渲染、空间变换与对象查询
笔记·游戏·3d·unity·游戏引擎
影寂ldy5 小时前
C# 五大加密算法全套实战(AES/DES对称、RSA非对称、MD5/SHA256哈希)
开发语言·c#·哈希算法
user-猴子5 小时前
还在手动复制粘贴处理Excel?用AI自动化办公
人工智能·自动化·excel
互联网底层民工5 小时前
异步 / 多线程并发(高频八股 · 详解版)
c#
逝水无殇5 小时前
C# 反射详解
开发语言·后端·c#