UnityはExcelファイルの読み込みを実装します

Unity には、Text テキストの内容を単純に読み取ることができる独自のクラス textAsset があることは誰もが知っています。しかし、実際の開発ではexcelやjsonなどのファイル形式を扱うことになるので、今日はexcel文書を読み込む機能をどうすれば簡単に実現できるかを整理するのに時間がかかりました。

githubアドレス: githubプロジェクトアドレス

私の個人ブログ: wyryyds.github.io

まず、3 つの拡張ライブラリをインポートします。これは、Plugins (self-built) フォルダーの下に保存されます。

リンク: https://pan.baidu.com/s/1jRSOjiDvdoNyF0eSezz6Kw?pwd=twtn 抽出コード: twtn

まず 2 つのクラスをカスタマイズしましょう。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace Data
{
	[System.Serializable]
	public class Item
	{
		public uint itemId;  //uint为无符号整型。
		public string itemName;
		public uint itemPrice;
	}
	public class ItemManager : ScriptableObject
	{
		public Item[] dataArray;
	}
}

itemManager を Unity の ScriptableObject から継承させて、後でそのメソッドを呼び出せるようにします。

Excel ファイルを処理するための新しいスクリプトを作成します。

まず、2 つのフォルダーのパス名を取得するクラスを定義します。1 つは Excel ファイルのパスで、もう 1 つは生成するアイテムのパス名です。その後の操作がより直感的になるのは便利です。

public class ExcelConfig
	{
		public static readonly string excelsFolderPath = Application.dataPath + "/Excels/";

		public static readonly string assetPath = "Assets/Resources/DataAssets/";
	}

次に、クラスを定義し、Excel を読み取る関数と、データを項目に変換する関数を記述します。

 public class Excel_Tool
    {
        static DataRowCollection ReadExcel(string filePath, ref int columnNum, ref int rowNum)//使用关键字ref引用传值
        {
            FileStream stream = File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);

//FileStream是C#文件读写流的一种类,可以操作各种文件的读写。需使用命名空间System.IO
            IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
//IExcelDataReader 是c#用于操作Excel文件的类库。需使用命名空间system.ExcelDataReader

            DataSet result = excelReader.AsDataSet();
            //Tables[0] 下标0表示excel文件中第一张表的数据
            columnNum = result.Tables[0].Columns.Count;
            rowNum = result.Tables[0].Rows.Count;
            return result.Tables[0].Rows;
        }
        
        public static Item[] CreateItemArrayWithExcel(string filePath)
        {
            //获得表数据
            int columnNum = 0, rowNum = 0;
            DataRowCollection collect = ReadExcel(filePath, ref columnNum, ref rowNum);

            //根据excel的定义,第二行开始才是数据
            Item[] array = new Item[rowNum - 1];
            for (int i = 1; i < rowNum; i++)
            {
                Item item = new Item();
                //解析每列的数据
                item.itemId = uint.Parse(collect[i][0].ToString()); //使用parse转换
                item.itemName = collect[i][1].ToString();
                item.itemPrice = uint.Parse(collect[i][2].ToString());
                array[i - 1] = item;
            }
            return array;
        }

次に、パネルを作成するクラスを作成します。Editor から継承してパネルとエディタを作成します。

 public class ExcelBuild : Editor
    {

        [MenuItem("CustomEditor/CreateItemAsset")]
        public static void CreateItemAsset()
        {
            ItemManager manager = ScriptableObject.CreateInstance<ItemManager>();
            //赋值
            manager.dataArray = Excel_Tool.CreateItemArrayWithExcel(ExcelConfig.excelsFolderPath + "Item.xlsx");

            //确保文件夹存在
            if (!Directory.Exists(ExcelConfig.assetPath))
            {
                Directory.CreateDirectory(ExcelConfig.assetPath);
            }

            //asset文件的路径 要以"Assets/..."开始,否则CreateAsset会报错
            string assetPath = string.Format("{0}{1}.asset", ExcelConfig.assetPath, "Item");
            //生成一个Asset文件
            AssetDatabase.CreateAsset(manager, assetPath);
            AssetDatabase.SaveAssets();
            AssetDatabase.Refresh();
        }

最終的な全体のコードは次のとおりです。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Data;
using System.IO;
using System.Text;
using Excel;
using UnityEditor;
using Data;

public class ExcelTool : MonoBehaviour
{
     
	public class ExcelConfig
	{
		/// <summary>
		/// 存放excel表文件夹的的路径,本例xecel表放在了"Assets/Excels/"当中
		/// </summary>
		public static readonly string excelsFolderPath = Application.dataPath + "/Excels/";

		/// <summary>
		/// 存放Excel转化CS文件的文件夹路径
		/// </summary>
		public static readonly string assetPath = "Assets/Resources/DataAssets/";
	}

    public class Excel_Tool
    {
        static DataRowCollection ReadExcel(string filePath, ref int columnNum, ref int rowNum)
        {
            FileStream stream = File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
            IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);

            DataSet result = excelReader.AsDataSet();
            //Tables[0] 下标0表示excel文件中第一张表的数据
            columnNum = result.Tables[0].Columns.Count;
            rowNum = result.Tables[0].Rows.Count;
            return result.Tables[0].Rows;
        }
        /// <summary>
        /// 读取表数据,生成对应的数组
        /// </summary>
        /// <param name="filePath">excel文件全路径</param>
        /// <returns>Item数组</returns>
        public static Item[] CreateItemArrayWithExcel(string filePath)
        {
            //获得表数据
            int columnNum = 0, rowNum = 0;
            DataRowCollection collect = ReadExcel(filePath, ref columnNum, ref rowNum);

            //根据excel的定义,第二行开始才是数据
            Item[] array = new Item[rowNum - 1];
            for (int i = 1; i < rowNum; i++)
            {
                Item item = new Item();
                //解析每列的数据
                item.itemId = uint.Parse(collect[i][0].ToString());
                item.itemName = collect[i][1].ToString();
                item.itemPrice = uint.Parse(collect[i][2].ToString());
                array[i - 1] = item;
            }
            return array;
        }

        /// <summary>
        /// 读取excel文件内容
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <param name="columnNum">行数</param>
        /// <param name="rowNum">列数</param>
        /// <returns></returns>
        
    }
    public class ExcelBuild : Editor
    {

        [MenuItem("CustomEditor/CreateItemAsset")]
        public static void CreateItemAsset()
        {
            ItemManager manager = ScriptableObject.CreateInstance<ItemManager>();
            //赋值
            manager.dataArray = Excel_Tool.CreateItemArrayWithExcel(ExcelConfig.excelsFolderPath + "Item.xlsx");

            //确保文件夹存在
            if (!Directory.Exists(ExcelConfig.assetPath))
            {
                Directory.CreateDirectory(ExcelConfig.assetPath);
            }

            //asset文件的路径 要以"Assets/..."开始,否则CreateAsset会报错
            string assetPath = string.Format("{0}{1}.asset", ExcelConfig.assetPath, "Item");
            //生成一个Asset文件
            AssetDatabase.CreateAsset(manager, assetPath);
            AssetDatabase.SaveAssets();
            AssetDatabase.Refresh();
        }
    }

}

ブロガー Wang Wang Wang Zha Zha の投稿に感謝します。コードの実装は彼の投稿を参照しています: Unity は Excel のコンテンツを読み取ります table_Wang Wang Wang Zha Zha のブログ - CSDN blog_unity は Excel ファイルを読み取ります

またまた釣りの日です!

おすすめ

転載: blog.csdn.net/qq_62440805/article/details/124914923