Unity讀取Excel文件(附源代碼)
今天想弄個Unity讀取Excel的功能的,發現網上有許多方法,采用其中一種方法:加入庫文件 Excel.dll 和ICSharpCode.SharpZipLib.dll庫文件,(還有System.Data.dll也要拷貝進來,在Unity安裝路徑C:\Program Files\Unity\Editor\Data\Mono\lib\mono\unity中),代碼下載鏈接在最後。
使用時要註意1997-2003和2007版本的腳本不一樣:
然後編寫腳本DoExcel.cs:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Data;
using System.IO;
using Excel;
public class DoExcel {
public static DataSet ReadExcel(string path)
{
FileStream stream = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.Read);
// CreateOpenXmlReader用於讀取Excel2007版本及以上的文件
IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
DataSet result = excelReader.AsDataSet();
excelReader.Close();
return result;
}
public static List<DepenceTableData> Load(string path)
{
List<DepenceTableData> _data = new List<DepenceTableData>();
DataSet resultds = ReadExcel(path);
int column = resultds.Tables[0].Columns.Count;
int row = resultds.Tables[0].Rows.Count;
Debug.LogWarning(column + " " + row);
for(int i=1;i<row;i++)
{
DepenceTableData temp_data;
temp_data.instruct = resultds.Tables[0].Rows[i][0].ToString();
temp_data.word = resultds.Tables[0].Rows[i][1].ToString();
Debug.Log(temp_data.instruct + " " + temp_data.word);
_data.Add(temp_data);
}
return _data;
}
}
public struct DepenceTableData
{
public string word;
public string instruct;
}
再寫一個腳本PrintExcel.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class PrintExcel : MonoBehaviour {
public List<DepenceTableData> listdata;
void Start () {
Text T = GameObject.Find("Canvas/Text").GetComponent<Text>();
T.text = "";//清空一開始的文本
listdata = DoExcel.Load(Application.dataPath + "\\Data\\" + "Test2007.xlsx");
foreach(var listing in listdata)
{
print(listing.instruct + " " + listing.word);
T.text += (listing.instruct + " " + listing.word + "\n").ToString();
}
}
}
編寫Excel如下:
層級視圖如下:
Test2007.xlsx放到新建的Data文件夾下;
將PrintExcel拖拽到Main Camera腳本中,添加Canvas->Text用於顯示Excel提取的文本,編輯器運行如下:
發布時打開調試功能:
問題是發布exe之後,然後需要手動添加Excel文件到***_Data下,例如我的Excel放在Data文件夾:
運行後發現不能打開文件,報錯了!
發現需要添加I18N*.dll等一些列dll才能打開。添加時可以在編輯器的Plugins添加,也可以發布後在***_Data/Managed下面添加這些dll。
這些dll來自Unity安裝路徑C:\Program Files\Unity\Editor\Data\Mono\lib\mono\unity中。
添加好之後,便可以顯示文本!!!如下所示。
如果用
FileStream stream = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.Read);
IExcelDataReader excelReader = ExcelReaderFactory.CreateBinaryReader(stream);
打開Excel1997-2003文件。會發現不能顯示中文和字母,發布後也不能顯示,加上I18N*.dll也不能顯示。把Excel的編碼格式改成UTF-8也不能顯示。
打開Excel1997-2003文本顯示如下,中文和字母不能顯示:
查了一些資料都不能解決這個問題,奇了怪了,有誰知道的交流一下啊!
工程源代碼下載路徑:http://download.csdn.net/detail/u011423279/9865038
采用Unity5.5.1開發的,請用相近的版本打開,如果打開奔潰或報錯,則將工程下的Assets和ProjectSettings保留,其他全部刪除再重新打開
Unity讀取Excel文件(附源代碼)