Unity版本:Unity 2018.3.4f1
1、获取第三方开发包,GitHub地址:https://github.com/ExcelDataReader/ExcelDataReader
2、对下载的解决方案ExcelDataReader进行编译生成,生成相应的 dll 文件,并根据Unity的Scripting Runtime Version选择最低的版本,并将这三个库文件复制到 Assets/Plugins
下
3、准备用来读取的Excel表,我准备了两个两个Excel文件,分别是对应97-2003的UserLevel.xls 和 对应2007的UserLevel.xlsx,内容自己随意定义
直接上代码,都很简单,所以就没有添加注释
using ExcelDataReader;
using System.Collections.Generic;
using System.Data;
using System.IO;
using UnityEngine;
using UnityEngine.UI;
namespace ExcelData.DirectReading
{
public class ReadExcel : MonoBehaviour
{
public Text m_Message;
private string excelFilePath;
private Dictionary<int, List<string>> excelDataDic;
// Start is called before the first frame update
void Start()
{
excelDataDic = new Dictionary<int, List<string>>();
ReadExcelStream(0);
m_Message.text += new string('-', 70) + "\r\n";
ReadExcelStream(1);
}
// Update is called once per frame
void Update()
{
}
private void ReadExcelStream(int _type)
{
excelDataDic.Clear();
if (_type == 0)
{
excelFilePath = Application.dataPath + "/Resources/ExcelDataReader/UserLevel.xls";
}
else
{
excelFilePath = Application.dataPath + "/Resources/ExcelDataReader/UserLevel.xlsx";
}
FileStream fileStream = File.Open(excelFilePath, FileMode.Open, FileAccess.Read,
FileShare.Read);
IExcelDataReader dataReader;
if (_type == 0)
{
#region 读取 *.xls 文件
//ExcelReaderFactory.CreateBinaryReader:读取的excel的类型为(97 - 2003 format, *.xls)
dataReader = ExcelReaderFactory.CreateBinaryReader(fileStream);
#endregion
}
else
{
#region 读取 *.xlsx 文件
//ExcelReaderFactory.CreateOpenXmlReader:读取的excel的类型为(2007 format, *.xlsx)
dataReader = ExcelReaderFactory.CreateOpenXmlReader(fileStream);
#endregion
}
DataSet result = dataReader.AsDataSet();
dataReader.Close();
//列
int columns = result.Tables[0].Columns.Count;
//行
int rows = result.Tables[0].Rows.Count;
for (int i = 0; i < rows; i++)
{
List<string> temp = new List<string>();
for (int j = 0; j < columns; j++)
{
string value = result.Tables[0].Rows[i][j].ToString();
temp.Add(value);
}
excelDataDic.Add(i, temp);
}
Dictionary<int, List<string>>.Enumerator enumerator = excelDataDic.GetEnumerator();
while (enumerator.MoveNext())
{
List<string> list = enumerator.Current.Value;
string info = enumerator.Current.Key.ToString() + " :";
for (int i = 0; i < list.Count; i++)
{
info += " " + list[i];
}
m_Message.text += info + "\r\n";
}
}
}
}
选择调试模式发布,发布完成之后运行时发现报错
报错的原因是打包出来的程序下Resources
文件中不包含相应的Excel文件,需要人为的手动将对应的文件信息拷贝到Resources
中,再次运行时发现出现另外一个错误,错误信息如下:
通过各种百度和谷歌,在Unity官方论坛上找到一篇很早以前的文章,其中有相关的讨论,该篇文章的地址:https://answers.unity.com/questions/42955/codepage-1252-not-supported-works-in-editor-but-no.html
找到Unity的安装路径,如我的安装路径:C:\Program Files\Unity\Editor
,然后查找与 I18N
相关的 dll
文件,并将这些文件拷贝到 Assets/Plugins
下,具体路径如下,根据自己的Unity安装路径做出对应修改即可
再次发布,并将相应的文件拷贝到相应的位置并运行,运行结果与在编辑器中的运行结果相同