Unity实现读取Excel文件

我们都知道Unity有自带的类textAsset可以简单地读取Text文本的内容。但在实际的开发过程中,我们不可避免地会与excel 或者 json这些文件类型打交道,今天也是花了点时间,整理出来了如何简单地实现读取excel文档的功能。

github地址:github项目地址

本人个人博客:wyryyds.github.io

首先我们先导入三个拓展库。存放在文件夹Plugins(自建)下面。

链接: https://pan.baidu.com/s/1jRSOjiDvdoNyF0eSezz6Kw?pwd=twtn 提取码: twtn

我们先自定义两个类。

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文件。

先定义一个类,来获取两个文件夹路径名。一个是我们的excel文件的路径,一个是我们要生成的item的路径名。方便我们在后续的操作中更直观。

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

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

接着我们定义一个类,编写读取excel的函数,跟将数据转换到item的函数。

 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();
        }
    }

}

感谢博主王王王渣渣的帖子,代码的实现参照他的这篇帖子:Unity 读取Excel表的内容_王王王渣渣的博客-CSDN博客_unity读取excel文件

又是摸鱼的一天呐!

猜你喜欢

转载自blog.csdn.net/qq_62440805/article/details/124914923