unity 讀取excel
本文參考連結:http://www.xuanyusong.com/archives/2429
1.工程檔案里加入
下載連結http://exceldatareader.codeplex.com/
2.加入紅色引用。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using Excel;
using System.Data;
3.程式碼
public static List<float> tt = new List<float>();
public static List<float> ss = new List<float>();
public static List<float> vv = new List<float>();
public static List<float> aa = new List<float>();
string shuzi;//擷取的字串
float number;//轉換成數字
void Start()
{
XLSX();
onxie();
}
void Update()
{
}
//讀取xlsx,注意不要用unity直接開啟,否則會報錯。如果報錯,請重新放入一個表格。
private void XLSX()
{
FileStream stream = File.Open(Application.dataPath + "/Excel/jianchuang.xlsx", FileMode.Open, FileAccess.Read);
IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
DataSet result = excelReader.AsDataSet();
int columns = result.Tables[0].Columns.Count;
int rows = result.Tables[0].Rows.Count;
//print("列數" + columns);
//print("行數" + rows);
//從第二行開始輸出。
for (int i = 1; i < rows; i++)
{
for (int j = 0; j < columns; j++)
{
string nvalue = result.Tables[0].Rows[i][j].ToString();
//判斷擷取字串的長度。
if (nvalue.Length == 1)
{
//如果字串的長度為1;
shuzi = nvalue.Substring(0, 1);
}
else if (nvalue.Length == 2)
{
//如果字串的長度為2;
shuzi = nvalue.Substring(0, 2);
}
else if (nvalue.Length == 3)
{
//如果字串的長度為3;
shuzi = nvalue.Substring(0, 3);
}
else if (nvalue.Length == 4)
{
//如果字串的長度為大於4;
shuzi = nvalue.Substring(0, 4);
}
else if (nvalue.Length >= 5)
{
//如果字串的長度為大於4;
shuzi = nvalue.Substring(0, 5);
}
else
{
Debug.Log("存在空的字串!!!");
}
//字串轉化成字串。
try
{
number = float.Parse(shuzi);
}
catch
{
Debug.Log("字串沒有轉化成功!!!");
}
//Debug.Log("行數" + i + "列數" + j + ":" + number);
//把excel按照列存到列表裡面
switch (j)
{
case 0:
tt.Add(number);
break;
case 1:
ss.Add(number);
break;
case 2:
vv.Add(number);
break;
case 3:
aa.Add(number);
break;
}
}
}
}
public void onxie()
{
print("輸出一列的資料!");
for (int i = 0; i < tt.Count; i++)
{
print(tt[i]);
}
}
4.加入excel。
注意:要是修改excel表格裡面的資料不要再unity裡面雙擊,否則會報錯。
InvalidCastException: Cannot cast from source type to destination type.
System.Data.Common.DoubleDataContainer.DoCopyValue (System.Data.Common.DataContainer from, Int32 from_index, Int32 to_index)
System.Data.Common.DataContainer.CopyValue (System.Data.Common.DataContainer from, Int32 from_index, Int32 to_index)
System.Data.Common.RecordCache.CopyRecord (System.Data.DataTable fromTable, Int32 fromRecordIndex, Int32 toRecordIndex)
在外面改過之後,重新替換就行,雖然麻煩,但是不會報錯。要是忘記了,還是報錯了,就把裡面的excel表格刪掉,重新放一個就不會報錯了。具體原因不知道。
5.釋出出來的是這樣的。