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];//索引可修改
    }
}
相关推荐
ms365copilot3 小时前
算数据+做图表,Copilot Excel公式+图表联动
excel·copilot
是嘟嘟啊8 小时前
【Unity DOTS】EntityCommandBuffer 与 JobHandle
unity·ecs·dots·unity dots·job·burst·burstjob
雪隐9 小时前
WPF + MVVM 实战系列01-一个老狗回炉重造 WPF 的 12 天血泪史
sqlite·c#·mvvm
xcLeigh9 小时前
Unity基础:Camera相机组件详解——透视投影与正交投影的区别
数码相机·unity·游戏引擎
在世修行10 小时前
从零打造 C# 工业视觉检测系统(四):海康威视 MVS SDK 入门与相机枚举实战
数码相机·c#·视觉检测
神秘的MT11 小时前
C# WinForm Socket 服务器 + 串口转发
服务器·网络·学习·c#
玖玥拾11 小时前
Unity3D RPG 入门项目(二)移动 Bug 修复、环绕相机、NPC 任务系统、UI 穿透处理
unity·游戏引擎
ms365copilot12 小时前
在Copilot聊天中添加Word、Excel 和 PowerPoint 代理
word·excel·copilot
Smilecoc12 小时前
Excel之Subtotal:功能强大的统计函数
excel
Yasin Chen14 小时前
Unity UGUI RectMask2D 原理
unity·游戏引擎