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

75 lines
2.3 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System.Data;
using System.IO;
using System.Collections.Generic;
using UnityEngine;
#if UNITY_EDITOR
using Excel;
#endif
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)
{
#if UNITY_EDITOR
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;
#else
return null;
#endif
}
}
}