XLSRandomNameLoader.cs 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. 
  2. using CommonAI.Data;
  3. using CommonLang;
  4. using CommonLang.IO;
  5. using NPOI.HSSF.UserModel;
  6. using NPOI.SS.UserModel;
  7. using NPOI.XSSF.UserModel;
  8. using System;
  9. using System.Collections.Generic;
  10. using System.IO;
  11. using XmdsCommonServer.XLS.Data;
  12. using static XmdsCommonServer.XLS.Data.RandomName;
  13. namespace XmdsCommonServer.XLS
  14. {
  15. public class XLSRandomNameLoader : XLSLoader
  16. {
  17. private List<PrefixName> mPrefixName = new List<PrefixName>();
  18. private List<SuffixName> mSuffixName = new List<SuffixName>();
  19. private bool mHasData;
  20. public XLSRandomNameLoader(string path)
  21. {
  22. byte[] data = Resource.LoadData(path);
  23. if (data == null)
  24. {
  25. throw new Exception("Can not read xls file : " + path);
  26. }
  27. using (MemoryStream ms = new MemoryStream(data))
  28. {
  29. IWorkbook Workbook = null;
  30. if (path.Contains(".xlsx"))
  31. {
  32. Workbook = new XSSFWorkbook(ms);
  33. }
  34. else if (path.Contains(".xls"))
  35. {
  36. Workbook = new HSSFWorkbook(ms);
  37. }
  38. for (int si = 0; si < Workbook.NumberOfSheets; si++)
  39. {
  40. ISheet sheet = Workbook.GetSheetAt(si) as ISheet;
  41. try
  42. {
  43. if (sheet.SheetName == "Prefix")
  44. {
  45. foreach (PrefixName m in LoadSheet<PrefixName>(sheet))
  46. {
  47. mPrefixName.Add(m);
  48. }
  49. }
  50. else if (sheet.SheetName == "Suffix")
  51. {
  52. foreach (SuffixName m in LoadSheet<SuffixName>(sheet))
  53. {
  54. mSuffixName.Add(m);
  55. }
  56. }
  57. mHasData = mPrefixName.Count > 0 && mSuffixName.Count > 0;
  58. }
  59. catch (Exception error)
  60. {
  61. throw new Exception(string.Format("XLSZhanYaoDataLoader 初始化斩妖配置错误SheetName = {0},Error = {1}",
  62. sheet.SheetName, error.ToString()));
  63. }
  64. }
  65. }
  66. log.Info("XLSZhanYaoDataLoader 初始化怪物配置完成.");
  67. }
  68. public string GetRanomName()
  69. {
  70. if(!mHasData)
  71. {
  72. return null;
  73. }
  74. int indexPrefix = GlobalData.gRandom.Next() % this.mPrefixName.Count;
  75. int indexSuffix = GlobalData.gRandom.Next() % this.mSuffixName.Count;
  76. return this.mPrefixName[indexPrefix].prefix + this.mSuffixName[indexSuffix].suffix;
  77. }
  78. }
  79. }