Unity Excel 文件读取和写入

在网上看到很多Unity 的解析Excel 的文章,其中最经典的一篇莫过于雨凇Momo的Unity3D研究院之MAC&Windows跨平台解析Excel(六十五)

但是在使用的过程中还是碰到了不少的问题,在这里总结一下,希望能对看到此处的朋友一个帮助。

1.Excel的读取

需要加入库文件 Excel.dll 和ICSharpCode.SharpZipLib库文件,官方链接 http://exceldatareader.codeplex.com/

Excel文件

 

需要添加的命名空间

using Excel;

读取方法

 
  1. using UnityEngine;

  2. using Excel;

  3. using System.Data;

  4. using System.IO;

  5. using System.Collections.Generic;

  6.  
  7. public class ExcelAccess

  8. {

  9. public static string Excel = "Book";

  10.  
  11. //查询menu表

  12. public static List<Menu> SelectMenuTable()

  13. {

  14. string excelName = Excel + ".xlsx";

  15. string sheetName = "sheet1";

  16. DataRowCollection collect = ExcelAccess.ReadExcel(excelName, sheetName);

  17.  
  18. List<Menu> menuArray = new List<Menu>();

  19. for (int i = 1; i < collect.Count; i++)

  20. {

  21. if (collect[i][1].ToString() == "") continue;

  22.  
  23. Menu menu = new Menu

  24. {

  25. m_Id = collect[i][0].ToString(),

  26. m_level = collect[i][1].ToString(),

  27. m_parentId = collect[i][2].ToString(),

  28. m_name = collect[i][3].ToString()

  29. };

  30. menuArray.Add(menu);

  31. }

  32. return menuArray;

  33. }

  34.  
  35. /// <summary>

  36. /// 读取 Excel ; 需要添加 Excel.dll; System.Data.dll;

  37. /// </summary>

  38. /// <param name="excelName">excel文件名</param>

  39. /// <param name="sheetName">sheet名称</param>

  40. /// <returns>DataRow的集合</returns>

  41. static DataRowCollection ReadExcel(string excelName,string sheetName)

  42. {

  43. string path= Application.dataPath + "/" + excelName;

  44. FileStream stream = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.Read);

  45. IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);

  46.  
  47. DataSet result = excelReader.AsDataSet();

  48. //int columns = result.Tables[0].Columns.Count;

  49. //int rows = result.Tables[0].Rows.Count;

  50.  
  51. //tables可以按照sheet名获取,也可以按照sheet索引获取

  52. //return result.Tables[0].Rows;

  53. return result.Tables[sheetName].Rows;

  54. }

  55. }

 

这里逻辑很简单,如果有不懂得可以上Excel的文档里去看,但是这个Excel的库有一个限制,就是只能读不能写,并且只能在编辑器下用,如果打包出来加载时会报空指针异常,原因就不清楚了。

所以建议大家,让策划把Excel写好后,在编辑器下读取后用Unity 的ScriptableObject 类保存成Asset文件,可以在运行时更方便的读取。

ScriptableObject 使用

下面给出我的实现方式,大家可以根据自己实体类来写这个BookHolder;

1.编写BookHolder类

 
  1. using UnityEngine;

  2. using System.Collections.Generic;

  3.  
  4. /// <summary>

  5. /// 基于ScriptObject的BookHolder类

  6. /// </summary>

  7. public class BookHolder : ScriptableObject

  8. {

  9. public List<Menu> menus;

  10. }

 
  1. /// <summary>

  2. /// 菜单实体类

  3. /// </summary>

  4. [System.Serializable]

  5. public class Menu

  6. {

  7. public string m_Id;

  8. public string m_level;

  9. public string m_parentId;

  10. public string m_name;

  11. }

 

2.新建编辑器脚本,制作xxx.asset文件。

 
  1. using UnityEngine;

  2. using UnityEditor;

  3.  
  4. /// <summary>

  5. /// 利用ScriptableObject创建资源文件

  6. /// </summary>

  7. public class BuildAsset : Editor {

  8.  
  9. [MenuItem("BuildAsset/Build Scriptable Asset")]

  10. public static void ExcuteBuild()

  11. {

  12. BookHolder holder = ScriptableObject.CreateInstance<BookHolder>();

  13.  
  14. //查询excel表中数据,赋值给asset文件

  15. holder.menus = ExcelAccess.SelectMenuTable();

  16.  
  17. string path= "Assets/Resources/booknames.asset";

  18.  
  19. AssetDatabase.CreateAsset(holder, path);

  20. AssetDatabase.Refresh();

  21.  
  22. Debug.Log("BuildAsset Success!");

  23. }

  24. }


3.xxx.asset文件读取

 
  1. using UnityEngine;

  2.  
  3. /// <summary>

  4. /// 读取booknames的scriptObject文件

  5. /// 使用Resources直接读取

  6. /// </summary>

  7. public class ReadHolders : MonoBehaviour {

  8. readonly string assetName = "booknames";

  9.  
  10. void Start ()

  11. {

  12. BookHolder asset = Resources.Load<BookHolder>(assetName);

  13. foreach (Menu gd in asset.menus)

  14. {

  15. Debug.Log(gd.m_Id);

  16. Debug.Log(gd.m_level);

  17. Debug.Log(gd.m_parentId);

  18. Debug.Log(gd.m_name);

  19. }

  20. }

  21. }


好了,Excel的读取就到这里。接下来讲一下Excel 的写入,怎么生成一个Excel文件,并把数组或字典中的数据写入Excel中呢?

2.Excel 的写入

此时需要一个Excel.dll的姐妹,EPPlus.dll 官方链接 https://epplus.codeplex.com/releases/view/118053

使用方法在官方的文档中都有,这里只贴出我的实现方式。

需要添加的命名空间

using OfficeOpenXml;

写入方法

 
  1. /// <summary>

  2. /// 写入 Excel ; 需要添加 OfficeOpenXml.dll;

  3. /// </summary>

  4. /// <param name="excelName">excel文件名</param>

  5. /// <param name="sheetName">sheet名称</param>

  6. public static void WriteExcel(string excelName, string sheetName)

  7. {

  8. //通过面板设置excel路径

  9. //string outputDir = EditorUtility.SaveFilePanel("Save Excel", "", "New Resource", "xlsx");

  10.  
  11. //自定义excel的路径

  12. string path = Application.dataPath + "/" + excelName;

  13. FileInfo newFile = new FileInfo(path);

  14. if (newFile.Exists)

  15. {

  16. //创建一个新的excel文件

  17. newFile.Delete();

  18. newFile = new FileInfo(path);

  19. }

  20.  
  21. //通过ExcelPackage打开文件

  22. using (ExcelPackage package = new ExcelPackage(newFile))

  23. {

  24. //在excel空文件添加新sheet

  25. ExcelWorksheet worksheet = package.Workbook.Worksheets.Add(sheetName);

  26. //添加列名

  27. worksheet.Cells[1, 1].Value = "ID";

  28. worksheet.Cells[1, 2].Value = "Product";

  29. worksheet.Cells[1, 3].Value = "Quantity";

  30. worksheet.Cells[1, 4].Value = "Price";

  31. worksheet.Cells[1, 5].Value = "Value";

  32.  
  33. //添加一行数据

  34. worksheet.Cells["A2"].Value = 12001;

  35. worksheet.Cells["B2"].Value = "Nails";

  36. worksheet.Cells["C2"].Value = 37;

  37. worksheet.Cells["D2"].Value = 3.99;

  38. //添加一行数据

  39. worksheet.Cells["A3"].Value = 12002;

  40. worksheet.Cells["B3"].Value = "Hammer";

  41. worksheet.Cells["C3"].Value = 5;

  42. worksheet.Cells["D3"].Value = 12.10;

  43. //添加一行数据

  44. worksheet.Cells["A4"].Value = 12003;

  45. worksheet.Cells["B4"].Value = "Saw";

  46. worksheet.Cells["C4"].Value = 12;

  47. worksheet.Cells["D4"].Value = 15.37;

  48.  
  49. //保存excel

  50. package.Save();

  51. }

  52. }


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

 

由于大家遇到问题较多,特附上工程地址

Git地址:https://git.oschina.net/passionyu/ExcelReadWrite.git

 

原文:https://blog.csdn.net/yupu56/article/details/50580277

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值