Unity Excel 檔案讀取和寫入
阿新 • • 發佈:2018-12-26
但是在使用的過程中還是碰到了不少的問題,在這裡總結一下,希望能對看到此處的朋友一個幫助。
1.Excel的讀取
Excel檔案
需要新增的名稱空間
using Excel;
讀取方法
using UnityEngine; using Excel; using System.Data; using System.IO; using System.Collections.Generic; public class ExcelAccess { public static string Excel = "Book"; //查詢menu表 public static List<Menu> SelectMenuTable() { string excelName = Excel + ".xlsx"; string sheetName = "sheet1"; DataRowCollection collect = ExcelAccess.ReadExcel(excelName, sheetName); List<Menu> menuArray = new List<Menu>(); for (int i = 1; i < collect.Count; i++) { if (collect[i][1].ToString() == "") continue; Menu menu = new Menu { m_Id = collect[i][0].ToString(), m_level = collect[i][1].ToString(), m_parentId = collect[i][2].ToString(), m_name = collect[i][3].ToString() }; menuArray.Add(menu); } return menuArray; } /// <summary> /// 讀取 Excel ; 需要新增 Excel.dll; System.Data.dll; /// </summary> /// <param name="excelName">excel檔名</param> /// <param name="sheetName">sheet名稱</param> /// <returns>DataRow的集合</returns> static DataRowCollection ReadExcel(string excelName,string sheetName) { string path= Application.dataPath + "/" + excelName; FileStream stream = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.Read); IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream); DataSet result = excelReader.AsDataSet(); //int columns = result.Tables[0].Columns.Count; //int rows = result.Tables[0].Rows.Count; //tables可以按照sheet名獲取,也可以按照sheet索引獲取 //return result.Tables[0].Rows; return result.Tables[sheetName].Rows; } }
這裡邏輯很簡單,如果有不懂得可以上Excel的文件裡去看,但是這個Excel的庫有一個限制,就是只能讀不能寫,並且只能在編輯器下用,如果打包出來載入時會報空指標異常,原因就不清楚了。
所以建議大家,讓策劃把Excel寫好後,在編輯器下讀取後用Unity 的ScriptableObject 類儲存成Asset檔案,可以在執行時更方便的讀取。
ScriptableObject 使用
下面給出我的實現方式,大家可以根據自己實體類來寫這個BookHolder;
1.編寫BookHolder類
using UnityEngine; using System.Collections.Generic; /// <summary> /// 基於ScriptObject的BookHolder類 /// </summary> public class BookHolder : ScriptableObject { public List<Menu> menus; }
/// <summary>
/// 選單實體類
/// </summary>
[System.Serializable]
public class Menu
{
public string m_Id;
public string m_level;
public string m_parentId;
public string m_name;
}
2.新建編輯器指令碼,製作xxx.asset檔案。
using UnityEngine; using UnityEditor; /// <summary> /// 利用ScriptableObject建立資原始檔 /// </summary> public class BuildAsset : Editor { [MenuItem("BuildAsset/Build Scriptable Asset")] public static void ExcuteBuild() { BookHolder holder = ScriptableObject.CreateInstance<BookHolder>(); //查詢excel表中資料,賦值給asset檔案 holder.menus = ExcelAccess.SelectMenuTable(); string path= "Assets/Resources/booknames.asset"; AssetDatabase.CreateAsset(holder, path); AssetDatabase.Refresh(); Debug.Log("BuildAsset Success!"); } }
3.xxx.asset檔案讀取
using UnityEngine;
/// <summary>
/// 讀取booknames的scriptObject檔案
/// 使用Resources直接讀取
/// </summary>
public class ReadHolders : MonoBehaviour {
readonly string assetName = "booknames";
void Start ()
{
BookHolder asset = Resources.Load<BookHolder>(assetName);
foreach (Menu gd in asset.menus)
{
Debug.Log(gd.m_Id);
Debug.Log(gd.m_level);
Debug.Log(gd.m_parentId);
Debug.Log(gd.m_name);
}
}
}
好了,Excel的讀取就到這裡。接下來講一下Excel 的寫入,怎麼生成一個Excel檔案,並把陣列或字典中的資料寫入Excel中呢?
2.Excel 的寫入
使用方法在官方的文件中都有,這裡只貼出我的實現方式。
需要新增的名稱空間
using OfficeOpenXml;
寫入方法
/// <summary>
/// 寫入 Excel ; 需要新增 OfficeOpenXml.dll;
/// </summary>
/// <param name="excelName">excel檔名</param>
/// <param name="sheetName">sheet名稱</param>
public static void WriteExcel(string excelName, string sheetName)
{
//通過面板設定excel路徑
//string outputDir = EditorUtility.SaveFilePanel("Save Excel", "", "New Resource", "xlsx");
//自定義excel的路徑
string path = Application.dataPath + "/" + excelName;
FileInfo newFile = new FileInfo(path);
if (newFile.Exists)
{
//建立一個新的excel檔案
newFile.Delete();
newFile = new FileInfo(path);
}
//通過ExcelPackage開啟檔案
using (ExcelPackage package = new ExcelPackage(newFile))
{
//在excel空檔案新增新sheet
ExcelWorksheet worksheet = package.Workbook.Worksheets.Add(sheetName);
//新增列名
worksheet.Cells[1, 1].Value = "ID";
worksheet.Cells[1, 2].Value = "Product";
worksheet.Cells[1, 3].Value = "Quantity";
worksheet.Cells[1, 4].Value = "Price";
worksheet.Cells[1, 5].Value = "Value";
//新增一行資料
worksheet.Cells["A2"].Value = 12001;
worksheet.Cells["B2"].Value = "Nails";
worksheet.Cells["C2"].Value = 37;
worksheet.Cells["D2"].Value = 3.99;
//新增一行資料
worksheet.Cells["A3"].Value = 12002;
worksheet.Cells["B3"].Value = "Hammer";
worksheet.Cells["C3"].Value = 5;
worksheet.Cells["D3"].Value = 12.10;
//新增一行資料
worksheet.Cells["A4"].Value = 12003;
worksheet.Cells["B4"].Value = "Saw";
worksheet.Cells["C4"].Value = 12;
worksheet.Cells["D4"].Value = 15.37;
//儲存excel
package.Save();
}
}
把上面的資料換成你自己的陣列和字典遍歷就OK 了。好了,今天的課程就到這裡,歡迎大神指教啊
由於大家遇到問題較多,特附上工程地址