unity读取excel表格需要引用excel.dll文件,下载地址:https://download.youkuaiyun.com/download/ThreePointsHeat/12859664
打包的时候需要把unity安装包里的解析中文字符串的dll文件也放在Plugins中:
代码如下:
/// <summary>
/// 读取xlsx表数据
/// </summary>
/// <returns></returns>
public List<string> LoadData()
{
// StreamingAssets目录下的 文物信息.xlsx文件的路径:Application.streamingAssetsPath + "/文物信息.xlsx"
FileStream fileStream = File.Open(Application.streamingAssetsPath + "/文物信息.xlsx", FileMode.Open, FileAccess.Read);
IExcelDataReader excelDataReader = ExcelReaderFactory.CreateOpenXmlReader(fileStream);
// 表格数据全部读取到result里
DataSet result = excelDataReader.AsDataSet();
// 获取表格有多少列
int colums = result.Tables[0].Columns.Count;
// 获取表格有多少行
int rows = result.Tables[0].Rows.Count;
// 根据行列依次打印表格中的每个数据
List<string> excelDta = new List<string>();
//第一行为表头,不读取
for (int i = 1; i < rows; i++)
{
value = null;
all = null;
for (int j = 0; j < colums; j++)
{
// 获取表格中指定行指定列的数据
value = result.Tables[0].Rows[i][j].ToString();
if(value == "")
{
continue;
}
all = all + value + "|";
}
if(all != null)
{
Debug.Log(all);
excelDta.Add(all);
}
}
return excelDta;
}
结果如下: