1.课前准备准备三个文件,Excel.dll, ICSharpCode.SharpZipLib.dll, System.Data.dll,
如图:
下载地址:链接:https://pan.baidu.com/s/1B2Sue9iw4qWzwjb1uJ6bPQ 提取码:vkxk
2.在unity3d里边建Plugins文件夹并将三个文件拖入,如下图:
3.建立一个空物体建立脚本,ReadExcel.cs,代码如下:
using UnityEngine;
using System.IO;
using Excel;
using System.Data;
public class ReadExcel : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
//1.打开文件,创建一个文件流操作对象
FileStream fileStream = new FileStream(Application.streamingAssetsPath+"/"+ "人物.xlsx", FileMode.Open,FileAccess.Read);
//2.创建一个excel读取类
IExcelDataReader reader = ExcelReaderFactory.CreateOpenXmlReader(fileStream);
//方法1:读取
while (reader.Read())
{
string name = reader.GetString(0);
string birth = reader.GetString(1);
string brief = reader.GetString(2);
Debug.Log("姓名:" + name + " --- " + "生卒:" + birth + " --- " + "简介:" + brief);
}
//方法2:读取
//DataSet result = reader.AsDataSet();
//获取行数
//int rows = result.Tables[0].Rows.Count;
//获取列数
//int column = result.Tables[0].Columns.Count;
//for (int i = 0; i < rows; i++)
//{
// 获取i行的第一列数据
// string name = result.Tables[0].Rows[i][0].ToString();
// 获取i行的第二列数据
// string birth = result.Tables[0].Rows[i][1].ToString();
// 获取i行的第三列数据
// string brief = result.Tables[0].Rows[i][2].ToString();
// Debug.Log("姓名:" + name + " --- " + "生卒:" + birth + " --- " + "简介:" + brief);
//}
}
}
?4.两种方法运行结果如下:
?5.提一下第二种方法,excel文档格式必须是.xlsx
|