mergemilitary/Assets/MMOModule/Scripts/MMOTable/MMOTableBase.cs

75 lines
2.3 KiB
C#
Raw Normal View History

2022-07-04 11:17:39 +00:00
using System.Data;
using System.IO;
using System.Collections.Generic;
using UnityEngine;
2022-08-31 11:45:55 +00:00
#if UNITY_EDITOR
using Excel;
#endif
2022-07-04 11:17:39 +00:00
namespace MMO
{
public abstract class MMOTableBase<T, U> : ScriptableObject where T : ScriptableObject
{
private static T mInstance;
public static T Instance
{
get
{
if (mInstance == null)
{
mInstance = Resources.Load<T>("MMOTable/" + typeof(T).Name);
}
return mInstance;
}
}
[SerializeField]protected List<U> mDataList;
public abstract U GetData(int pID);
protected abstract U ParseData(DataRow pCollection);
public void ParseExcel(string pFilePath)
{
int tColNum = 0, tRowNum = 0;
Debug.Log(pFilePath);
DataRowCollection tCollection = ReadExcelContext(pFilePath, ref tColNum, ref tRowNum);
Debug.Log(typeof(T).Name + ": 列数_" + tColNum + " 行数_" + tRowNum);
// 第一行变量名,循环列
//for (int i = 0; i < tColNum; i++)
//{
//}
//第二行开始才是数据,循环行
mDataList = new List<U>(tRowNum - 1);
for (int i = 1; i < tRowNum; i++)
{
mDataList.Add(ParseData(tCollection[i]));
}
}
/// <summary>
/// 读Excel
/// </summary>
/// <param name="pFilePath">文件路径</param>
/// <param name="pColNum">行数</param>
/// <param name="pRowNum">列数</param>
/// <returns></returns>
private DataRowCollection ReadExcelContext(string pFilePath, ref int pColNum, ref int pRowNum)
{
2022-08-31 11:45:55 +00:00
#if UNITY_EDITOR
2022-07-04 11:17:39 +00:00
FileStream stream = File.Open(pFilePath, FileMode.Open, FileAccess.Read, FileShare.Read);
IExcelDataReader excelReader = ExcelReaderFactory.CreateBinaryReader(stream);
DataSet result = excelReader.AsDataSet();
// Tables[0] 下标0表示excel文件中第一张表的数据
pColNum = result.Tables[0].Columns.Count;
pRowNum = result.Tables[0].Rows.Count;
return result.Tables[0].Rows;
2022-08-31 11:45:55 +00:00
#else
return null;
#endif
2022-07-04 11:17:39 +00:00
}
}
}