1.课前准备准备三个文件,Excel.dll, ICSharpCode.SharpZipLib.dll, System.Data.dll,
如图:![](https://img-blog.csdnimg.cn/20210713175715826.png)
下载地址:链接:https://pan.baidu.com/s/1B2Sue9iw4qWzwjb1uJ6bPQ
提取码:vkxk
2.在unity3d里边建Plugins文件夹并将三个文件拖入,如下图:
![](https://img-blog.csdnimg.cn/2021071317592815.png)
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.两种方法运行结果如下:
![](https://img-blog.csdnimg.cn/20210713182500245.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L20wXzM4MTE2NDU2,size_16,color_FFFFFF,t_70)
5.提一下第二种方法,excel文档格式必须是.xlsx
6.注意,如果你的unity3d版本是2019.4及以上,需要在Plugins下添加一下来文件,不然打包exe中读取不到数据
![](https://img-blog.csdnimg.cn/ea53994efb3a4ba0909e58c6ae5f137e.png)
7.上面文件可在unity3d对应版本安装包得到D:\Program Files\Unity2019_4\Editor\Data\MonoBleedingEdge\lib\mono\unity
![](https://img-blog.csdnimg.cn/f6fa0828fe39409fab8c4b92c6f1364f.png?x-oss-process=image/watermark,type_ZHJvaWRzYW5zZmFsbGJhY2s,shadow_50,text_Q1NETiBATWFvX0h1aQ==,size_20,color_FFFFFF,t_70,g_se,x_16)