使用Excel作为配置的优势
使用Excel作为配置文件有相对普通的文本文档/json等类型的配置文件有一个更好的优点,更易于编辑,更易读.譬如上面的例子,我可以制作一个人员名单,可以记录它们的姓名,年龄等信息,每一行就是一个对象,该表就是一个List.
环境准备
选择右侧release版本中较新的版本就可以
一般下载前两个,将拓展名改为能解压的类型(7z,zip等),然后解压在lib中找到dll,一般选择.netstandard2.0/2.1.放到Unity项目的Plugins文件夹下,后两个是源代码,大佬可以拿过来自己修改编译.
代码
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.IO;
using ExcelDataReader;//引入命名空间
using UnityEngine;
namespace Project.Utility
{
public class Person
{
public string name;
public int age;
public int gender;
public string hobby;
}
public class GetConfigUtility
{
/// <summary>
/// 加载Excel配置,必须放在StreamingAssets/ConfigFiles下(必须放在StreamingAssets下)
/// </summary>
/// <param name="excelFileName">文件名(需加文件后缀)</param>
/// <returns>返回一个Dictionary(表名,表)</returns>
public Dictionary<string, DataTable> GetExcelConfig(string excelFileName)
{
//拼接路径
string path = Path.Combine(Application.streamingAssetsPath, "ConfigFiles", excelFileName);
//获得该Excel文件的流
using (var stream = File.Open(path, FileMode.Open, FileAccess.Read))
{
//这个流给到ExcelReaderFactory,创建一个ExcelReader对象
using (var reader = ExcelReaderFactory.CreateReader(stream))
{
// 配置 DataSet 读取
var conf = new ExcelDataSetConfiguration
{
ConfigureDataTable = _ => new ExcelDataTableConfiguration
{
UseHeaderRow = true // 使用第一行作为列标题
}
};
//实例一个字典,键是表名(因为可以获取很多张表),值是一个表的对象
Dictionary<string, DataTable> dataTableDic = new Dictionary<string, DataTable>();
var dataSet = reader.AsDataSet(conf);//获取一个DataSet对象
//从DataSet对象中的Tables属性中遍历所有的表
foreach (DataTable dataTable in dataSet.Tables)
{
dataTableDic.Add(dataTable.TableName, dataTable);
}
return dataTableDic;
}
}
}
//读取某个表转为List
public List<Person> GetPersonList(Dictionary<string, DataTable> excelDic)
{
var personList = new List<Person>();
DataTable t = excelDic["你的表名"];//索引器填表名拿到表
for (int i = 0; i < t.Rows.Count; i++)//Rows属性代表所有行
{
Person person = new Person();
//Rows[i]拿到具体的行,第一行被忽略,因为上面使用了ExcelDataSetConfiguration
//Rows[i][0]代表i行第0个元素,但是类型是obj
person.name = t.Rows[i][0].ToString();
person.gender = int.Parse(t.Rows[i][1].ToString());
person.age = int.Parse(t.Rows[i][2].ToString());
person.name = t.Rows[i][3].ToString();
personList.Add(person);
}
return personList;
}
}
}