unity读取excel表格中的单元格内容
unity 的.net需要改为4.X
需要的dll文件如下,将文件夹放在Plugins目录下
Eplus下载链接
免费下载,骑士精神万岁
// 总行数
public int rowNum;
// 总列数
private int columnNum;
// 一张表
private DataTable table;
// 所有的题目
public List<Subject> subjects;
/// <summary>
/// 读取第一张表,获取行数和列数,返回第一张表
/// </summary>
private DataTable ReadExcelGo(string filePath)
{
IExcelDataReader excelReader = null;
FileStream stream = File.Open(filePath, FileMode.Open, FileAccess.Read);
var str = filePath.Split('.');
if (str[1] == "xlsx")
{
excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
}
if (str[1] == "xls")
{
excelReader = ExcelReaderFactory.CreateBinaryReader(stream);
}
DataSet result = excelReader.AsDataSet();
stream.Close();<br> //获取有效的行列数
columnNum = result.Tables[0].Columns.Count;
rowNum = result.Tables[0].Rows.Count;
return result.Tables[0];
}
/// <summary>
/// 生成题目
/// </summary>
private void SpawnSubject()
{
table = ReadExcelGo(Application.streamingAssetsPath + "/exam.xlsx");
for (int r = 1; r < rowNum; r++)
{
Subject sub = new Subject();
//读取所有的行
object[] rowObjs = table.Rows[r].ItemArray;
//读取每一行的每一列
for (int c = 0; c < columnNum; c++)
{
if (c == 0)
{<br> //读取每个单元格的内容
//第一列 为题目类型
string str = rowObjs[c].ToString();
switch (str)
{
case "1": //单选
sub.subType = SubjectType.Single;
break;
case "2": //多选
sub.subType = SubjectType.Multiple;
break;
case "3": //判断
sub.subType = SubjectType.Judge;
break;
}
}
else if (c == 1)
{
//第二列 为题干
sub.subTitle = rowObjs[c].ToString();
}
else if (c == 2)
{
//第三列 为选项A
sub.A = rowObjs[c].ToString();
}
else if (c == 3)
{
//第四列 为选项B
sub.B = rowObjs[c].ToString();
}
else if (c == 4)
{
//第五列 为选项C
sub.C = rowObjs[c].ToString();
}
else if (c == 5)
{
//第六列 为选项D
sub.D = rowObjs[c].ToString();
}
else if (c == 6)
{
//第七列 为正确答案
string str = rowObjs[c].ToString();
sub.currentAnswer = str.Split(',');
}
else if (c == 7)
{
//第八列 为分值
sub.score = float.Parse(rowObjs[c].ToString());
}
}
subjects.Add(sub);
}
}