ExcelHelper.cs 3.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Data;
  4. using UnityEngine;
  5. using System.IO;
  6. using ExcelDataReader;
  7. using System.Reflection;
  8. using OfficeOpenXml;
  9. /// <summary>
  10. /// Excel帮助类
  11. /// </summary>
  12. public class ExcelHelper
  13. {
  14. /// <summary>
  15. /// 从Excel文件读取信息
  16. /// </summary>
  17. /// <param name="tableName">文件路径名(需要有文件后缀)</param>
  18. /// <param name="headCount">表头</param>
  19. /// <returns></returns>
  20. public static List<T> ReadInfoFromExcel<T>(string filedPath, int headCount)
  21. {
  22. List<T> tmpTs = new List<T>();
  23. using (FileStream fileStream = File.Open(filedPath, FileMode.Open, FileAccess.Read))
  24. {
  25. using (IExcelDataReader dataReader = ExcelReaderFactory.CreateReader(fileStream))
  26. {
  27. //拿Excel第一张表
  28. DataTable tmpDataTable = dataReader.AsDataSet().Tables[0];
  29. //类中变量
  30. FieldInfo[] tmpFileInfos = typeof(T).GetFields();
  31. //匹配数据
  32. if (tmpFileInfos.Length != tmpDataTable.Columns.Count)
  33. {
  34. Debug.LogError($"转换数据与{filedPath}的元素数量不相同,请检查!!!");
  35. return tmpTs;
  36. }
  37. for (int i = headCount; i < tmpDataTable.Rows.Count; i++)
  38. {
  39. T tmpT = Activator.CreateInstance<T>();
  40. for (int j = 0; j < tmpFileInfos.Length; j++)
  41. {
  42. FieldInfo tmpFieldInfo = tmpFileInfos[j];
  43. tmpFieldInfo.SetValue(tmpT, tmpDataTable.Rows[i][j].ToString());
  44. }
  45. tmpTs.Add(tmpT);
  46. }
  47. }
  48. }
  49. return tmpTs;
  50. }
  51. /// <summary>
  52. /// 将数据信息写入到Excel文件中
  53. /// </summary>
  54. /// <typeparam name="T">类型</typeparam>
  55. /// <param name="ts">信息</param>
  56. /// <param name="filePath">全路径+后缀</param>
  57. public static bool WriteInfoToExcel<T>(string filePath, List<T> ts)
  58. {
  59. using (ExcelPackage package = new ExcelPackage())
  60. {
  61. if (package.Workbook.Worksheets.Count == 0) package.Workbook.Worksheets.Add("Sheet1");
  62. ExcelWorksheet sheet = package.Workbook.Worksheets["Sheet1"];
  63. FieldInfo[] tmpFieldInfos = typeof(T).GetFields();
  64. //写入标题
  65. for (int i = 1; i < tmpFieldInfos.Length + 1; i++) sheet.Cells[1, i].Value = tmpFieldInfos[i -1].Name;
  66. //写入数据
  67. for (int i = 2; i < ts.Count + 2; i++)
  68. {
  69. for (int j = 1; j < tmpFieldInfos.Length + 1; j++)
  70. {
  71. sheet.Cells[i, j].Value = tmpFieldInfos[j - 1].GetValue(ts[i - 2]);
  72. }
  73. }
  74. FileInfo tmpFileInfo = new FileInfo(filePath);
  75. //如果不存在表格就创建表格
  76. if (!tmpFileInfo.Exists) tmpFileInfo.Create().Dispose();
  77. package.SaveAs(tmpFileInfo);
  78. }
  79. return false;
  80. }
  81. }