Unity读取excel读取表格数据
继读取Excel数据,当数据表格多后为方便多表格读取,添加泛型方法
public class LocalDataBase: ScriptableObject { public T[] data; } public class LocalFile : LocalDataBase { }
为方便统一,这里面使用数组的保存数据
2.定义ExcelRead静态类 并添加调用方法public static class ExcelRead
{
///
/// 提供给编辑器调用
///
/// 返回数据
/// 文件路径
/// 文件名字
///
public static T[] GetExcelData(string filePath, string name)
{
switch (name)
{
case "File":
return GetFileData(filePath) as T[];
default:
Debug.LogError($"{name}未定义读取方法");
break;
}
return null;
}
//新增一个表格 可在此处添加新的读取方法.....
//并在GetExcelData里case字段
static int[] GetFileData(string filePath)
{
int columnNum = 0, rowNum = 0;
DataRowCollection collect = ReadExcel(filePath, ref columnNum, ref rowNum);
List list = new List();
for (int i = 1; i < rowNum; i++)
{
if (collect[i].IsNullRow(columnNum)) continue;
list.Add(collect[i].ToInt(0));
}
return list.ToArray();
}
///
/// 读取excel文件内容
///
/// 文件路径
/// 行数
/// 列数
///
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;
}
}
3.保存数据到指定文件 创建ExcelReadEditor类
public class ExcelReadEditor : Editor
{
//例
[MenuItem("Excel/读取File数据")]
public static void CreateFileData()
{
GetLocalData("File");
}
///
/// 泛型创建 保存本地数据
///
/// 保存到本地继承LocalDataBase数据类
/// 一个excel数据类
/// Excel文件名字 此处转出的数据也以此作为命名
public static void GetLocalData(string fileName) where T : LocalDataBase
{
T t = CreateInstance();
//这里以根目录下的excel文件夹举例
string filePath =Application.dataPath + "/Excel/" + fileName + ".xlsx";
t.data = ExcelRead.GetExcelData(filePath, fileName);
if (t.data == null) Debug.LogError("数据读取错误");
//保存到Resources/Data路径下 可做修改
string savePath = "Assets/Resources/Data/" + fileName + ".asset";
AssetDatabase.CreateAsset(t, savePath);
AssetDatabase.SaveAssets();
AssetDatabase.Refresh();
Debug.Log($"读取{fileName}数据成功");
}
}
为方便一键读取该类所有数据方法 添加批量读取
*注意方法名字以Create开头 例:CrateFileData()
[MenuItem("Excel/批量读表")]
public static void ReadAllExcel()
{
Type typeInfo = typeof(ExcelReadEditor);
MethodInfo[] methodInfo = typeInfo.GetMethods();
foreach (MethodInfo mInfo in methodInfo)
{
if (mInfo.ToString().StartsWith("Void Create"))
{
mInfo.Invoke(null, null);
}
}
Debug.Log("读取全部表成功");
}
4.添加DataRow拓展方法 方便数据类型转换
public static class ExcelExtensions
{
public static int ToInt(this DataRow dataRow, int colum)
{
int num = 0;
if (int.TryParse(dataRow[colum].ToString(), out num))
{
return num;
}
Debug.LogWarning($" ToInt error -> {colum}colum is empty");
return 0;
}
}
这里数据类型比较多,就没有全部展示。这里添加一个资源包链接里面有两个Excel的举例
下载下来可以直接使用
完整项目资源
提取码:n4bk



