Unity3D中MAC&Windows跨平臺解析Excel的程式碼
在Unity3D中,Mac下解析Excel ,這東西在Windows下有N種方法可以解析,但是在MAC上基本上都是不相容的。。一般 Excel的格式分為兩種一種是 .xls 還有一種是.xlsx ,這裡我們只說.xlsx 。
那麼這裡我就是在通過程式碼來解析UserLevel.xlsx了,程式碼比較簡單我就不註釋了。 這個例子我在MAC和Windows下都試驗過都能很好的執行。喔對,這裡我還引入了System.Data.dll 因為這裡我使用了DataSet來遍歷資料表。
01using System;
02using System.Collections.Generic;
03using System.Linq;
04using System.Text;
05using System.Text.RegularExpressions;
06using System.IO;
07using Excel;
08using System.Data;
09
10public class NewBehaviourScript : MonoBehaviour
11{
12 void Start ()
13 {
14 XLSX();
15
16 }
17
18 void XLSX()
19 {
20 FileStream stream = File.Open(Application.dataPath + "/UserLevel.xlsx", FileMode.Open, FileAccess.Read);
21 IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
22
23 DataSet result = excelReader.AsDataSet();
24
25 int columns = result.Tables[0].Columns.Count;
26 int rows = result.Tables[0].Rows.Count;
27
28 for(int i = 0; i< rows; i++)
29 {
30 for(int j =0; j < columns; j++)
31 {
32 string nvalue = result.Tables[0].Rows[i][j].ToString();
33 Debug.Log(nvalue);
34 }
35 }
36 }
37
38}
最好不要在程式執行時去動態解析這個Excel 。我的做法是把利用這個類庫把Excel裡面的資料讀取出來,然後自己用File在去把資料寫在別的檔案中,方面以後加密拓展等等。