Unity Excel 文件读取和写入

来源:互联网 发布:五线谱翻译简谱软件 编辑:程序博客网 时间:2024/05/16 02:21
在网上看到很多Unity 的解析Excel 的文章,其中最经典的一篇莫过于雨凇Momo的Unity3D研究院之MAC&Windows跨平台解析Excel(六十五)
但是在使用的过程中还是碰到了不少的问题,在这里总结一下,希望能对看到此处的朋友一个帮助。
Excel的读取,
需要加入库文件 Excel.dll 和ICSharpCode.SharpZipLib库文件,官方链接 http://exceldatareader.codeplex.com/
[csharp] view plain copy
  1. using Excel;  
  2. using System.Data;  
Excel文件读取和转换List格式
[csharp] view plain copy
  1. public class ExcelAccess  
  2. {  
  3.     public static string ExcelName = "Book.xlsx";  
  4.     public static string[] SheetNames = { "sheet1""sheet2""sheet3""sheet4" };  
  5.   
  6.     public static List<Menu> SelectMenuTable(int tableId)  
  7.     {  
  8.         DataRowCollection collect = ExcelAccess.ReadExcel(SheetNames[tableId - 1]);  
  9.         List<Menu> menuArray = new List<Menu>();  
  10.   
  11.         for (int i = 1; i < collect.Count; i++)  
  12.         {  
  13.             if (collect[i][1].ToString() == ""continue;  
  14.   
  15.             Menu menu = new Menu();  
  16.             menu.m_Id = collect[i][0].ToString();  
  17.             menu.m_level = collect[i][1].ToString();  
  18.             menu.m_parentId = collect[i][2].ToString();  
  19.             menu.m_name = collect[i][3].ToString();  
  20.             menuArray.Add(menu);  
  21.         }  
  22.         return menuArray;  
  23.     }  
  24.   
  25.     /// <summary>  
  26.     /// 读取 Excel 需要添加 Excel; System.Data;  
  27.     /// </summary>  
  28.     /// <param name="sheet"></param>  
  29.     /// <returns></returns>  
  30.     static DataRowCollection ReadExcel(string sheet)  
  31.     {  
  32.         FileStream stream = File.Open(FilePath(ExcelName), FileMode.Open, FileAccess.Read, FileShare.Read);  
  33.         IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);  
  34.   
  35.         DataSet result = excelReader.AsDataSet();  
  36.         //int columns = result.Tables[0].Columns.Count;  
  37.         //int rows = result.Tables[0].Rows.Count;  
  38.         return result.Tables[sheet].Rows;  
  39.     }  
  40. }  

这里逻辑很简单,如果有不懂得可以上Excel的文档里去看,但是这个Excel的库有一个限制,就是只能读不能写,并且只能在编辑器下用,如果打包出来加载时会报空指针异常,原因就不清楚了,所以建议大家,让策划把Excel写好后,在编辑器下读取后用Unity 的ScriptableObject 存起来,然后保存成Asset文件,可以在运行时更方便的读取。
下面给出我的实现方式,大家可以根据自己实体类来写这个StrignHolder;
StringHolder类
[csharp] view plain copy
  1. using UnityEngine;  
  2. using System.Collections.Generic;  
  3.   
  4. public class BookElementHolder : ScriptableObject  
  5. {  
  6.     public List<Menu> menus1;  
  7.     public List<Menu> menus2;  
  8.     public List<Menu> menus3;  
  9.     public List<Good> goods;  
  10. }  
制作Asset编辑器(可以把Asset达成AssetBundle的包,然后用WWW读取)
[csharp] view plain copy
  1. [MenuItem("Assetbundles/Create Assetbundles")]  
  2.     public static void ExcuteBuild()  
  3.     {  
  4.           
  5.         BookElementHolder holder = ScriptableObject.CreateInstance<BookElementHolder>();  
  6.   
  7.         holder.menus1 = ExcelAccess.SelectMenuTable(1);  
  8.         holder.menus2 = ExcelAccess.SelectMenuTable(2);  
  9.         holder.menus3 = ExcelAccess.SelectMenuTable(3);  
  10.         holder.goods = ExcelAccess.SelectGoodTable();  
  11.   
  12.         AssetDatabase.CreateAsset(holder, HolderPath);  
  13.         AssetImporter import = AssetImporter.GetAtPath(HolderPath);  
  14.         import.assetBundleName = "booknames";  
  15.   
  16.         BuildPipeline.BuildAssetBundles("Assets/Abs");  
  17.   
  18.         Debug.Log("BuildAsset Success!");  
  19.     }  

Asset读取方式
[csharp] view plain copy
  1. public string assetName = "bonenames";  
  2.     public void readAsset()  
  3.     {  
  4.         Object asset = Resources.Load<Object>(assetName);  
  5.         BookElementHolder ceh = (BookElementHolder)asset;  
  6.         foreach (Good gd in ceh.goods)  
  7.         {  
  8.             Debug.Log(gd.m_name);  
  9.         }  
  10.     }  

好了,Excel的读取就到这里,接下来讲一下Excel 的写入,怎么生成一个Excel文件,并把数组或字典中的数据写入Excel中呢?
此时需要一个Excel.dll的姐妹,EPPlus.dll 官方链接 https://epplus.codeplex.com/releases/view/118053
使用方法在官方的文档中都有,这里只贴出我的实现方式。
需要添加的命名空间
[csharp] view plain copy
  1. using OfficeOpenXml;  
写入方法
[csharp] view plain copy
  1. public static void WriteExcel(string outputDir)  
  2.     {  
  3.         //string outputDir = EditorUtility.SaveFilePanel("Save Excel", "", "New Resource", "xlsx");  
  4.         FileInfo newFile = new FileInfo(outputDir);  
  5.         if (newFile.Exists)  
  6.         {  
  7.             newFile.Delete();  // ensures we create a new workbook  
  8.             newFile = new FileInfo(outputDir);  
  9.         }  
  10.         using (ExcelPackage package = new ExcelPackage(newFile))  
  11.         {  
  12.             // add a new worksheet to the empty workbook  
  13.             ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("Sheet1");  
  14.             //Add the headers  
  15.             worksheet.Cells[1, 1].Value = "ID";  
  16.             worksheet.Cells[1, 2].Value = "Product";  
  17.             worksheet.Cells[1, 3].Value = "Quantity";  
  18.             worksheet.Cells[1, 4].Value = "Price";  
  19.             worksheet.Cells[1, 5].Value = "Value";  
  20.   
  21.             //Add some items...  
  22.             worksheet.Cells["A2"].Value = 12001;  
  23.             worksheet.Cells["B2"].Value = "Nails";  
  24.             worksheet.Cells["C2"].Value = 37;  
  25.             worksheet.Cells["D2"].Value = 3.99;  
  26.   
  27.             worksheet.Cells["A3"].Value = 12002;  
  28.             worksheet.Cells["B3"].Value = "Hammer";  
  29.             worksheet.Cells["C3"].Value = 5;  
  30.             worksheet.Cells["D3"].Value = 12.10;  
  31.   
  32.             worksheet.Cells["A4"].Value = 12003;  
  33.             worksheet.Cells["B4"].Value = "Saw";  
  34.             worksheet.Cells["C4"].Value = 12;  
  35.             worksheet.Cells["D4"].Value = 15.37;  
  36.   
  37.             //save our new workbook and we are done!  
  38.             package.Save();  
  39.         }  
  40.     }  

把上面的数据换成你自己的数组和字典遍历就OK 了。好了,今天的课程就到这里,欢迎大神指教啊

由于大家遇到问题较多,特附上工程地址
Git地址:https://git.oschina.net/passionyu/ExcelReadWrite.git
原创粉丝点击