写在前面
看了网上很多的教程之后,决定经过自己的学习之后,总结出来一个傻瓜式教程,以方便向我一样自学的小伙伴,不要走太多的弯路。
网上很多的教程都提到了Momo大佬的博客Unity3D研究院之MAC&Windows跨平台解析Excel(六十五)但是本文中提到的Excel 和 ICSharpCode.SharpZipLib第三方开发包却没有明确给出。这里直接给出这个第三方开发包的Github地址。
现在开始第一步,首先我们要获取这个Excel的第三方库。打开上面的Github地址。克隆库到本地。然后解压Zip后打开文件夹。

用VS打开Vs解决方案.sln,生成第三方库。

之后在工程目录下找到下面的这个文件夹中选中的三个文件。

为什么要选择net35是因为Unity2018.2.15f1的当前版本中的editor只对net3.5的版本支持。
然后复制这三个文件到Unity工程资源目录: Assets/Plugins/
下。现在我们就算是做好了第一步的准备。
第二步,创建脚本使用VS打开脚本。这里附上我测试时的一段程序。
using System.IO;
using System.Data;
using ExcelDataReader;
public class ReadExcel : MonoBehaviour {
private string FilePath;
private void Start()
{
FilePath = Application.dataPath + "/Resources/LevelsInfo/LevelList.xlsx";
ReadExcelStream();
Debug.Log(FilePath);
}
void ReadExcelStream()
{
FileStream stream = File.Open(FilePath, FileMode.Open, FileAccess.Read);
IExcelDataReader excelDataReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
DataSet result = excelDataReader.AsDataSet();
int columns = result.Tables[0].Columns.Count;
int rows = result.Tables[0].Rows.Count;
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < columns; j++)
{
string nvalue = result.Tables[0].Rows[i][j].ToString();
Debug.Log(nvalue);
}
}
excelDataReader.Close();
}
}
但是这里会报错

然后这里就需要使用NuGet 程序包管理器 添加第三方依赖。

如上打开程序包管理器控制台
使用Install-Package ExcelDataReader
来添加第三方译依赖。

依赖添加完了,之后就要再添加System.Data.dll文件到工程中。
根据 u3d引用System.Data问题的一些解决办法 这篇博客,说明需要把Unity安装路径下u3d\Editor\Data\Mono\lib\mono\2.0\System.Data.dll
文件直接复制到工程目录下直接using来解决错误。
到这里,就可以正常使用这个Excel第三方库了。下面是脚本输出结果。


关于AsDataSet()方法我还没有总结,但是在官方的Github的下面有相关的介绍和例子,可以看看。
网友评论