ExcelFileReader.cs 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131
  1. using NPOI.SS.Formula.Functions;
  2. using NPOI.SS.UserModel;
  3. using InABox.Core;
  4. using System;
  5. using System.Collections;
  6. using System.Collections.Generic;
  7. using System.IO;
  8. using System.Linq;
  9. using System.Text;
  10. using System.Threading.Tasks;
  11. using static NPOI.HSSF.UserModel.HeaderFooter;
  12. namespace InABox.Scripting
  13. {
  14. public class ExcelFileReader : ITabularFileReader
  15. {
  16. private IEnumerator<IRow> rows;
  17. public Dictionary<string, int> Columns { get; set; }
  18. public bool EndOfData { get; private set; }
  19. private IRow _row;
  20. public ExcelFileReader(Stream stream)
  21. {
  22. rows = new Spreadsheet(stream).GetSheet(0).RowEnumerator();
  23. Columns = new Dictionary<string, int>();
  24. SkipLine();
  25. }
  26. public IList<string> ReadLineValues()
  27. {
  28. var results = new List<string>();
  29. if (!EndOfData)
  30. {
  31. foreach (var cell in _row.Cells())
  32. {
  33. results.Add(cell.GetValue());
  34. }
  35. SkipLine();
  36. }
  37. return results;
  38. }
  39. public bool ReadHeader()
  40. {
  41. Columns.Clear();
  42. if (EndOfData)
  43. {
  44. return false;
  45. }
  46. int i = 0;
  47. foreach(var cell in _row.Cells())
  48. {
  49. var column = cell.GetValue();
  50. if (!column.IsNullOrWhiteSpace())
  51. {
  52. Columns.Add(column, i);
  53. }
  54. ++i;
  55. }
  56. SkipLine();
  57. return true;
  58. }
  59. public Dictionary<string, object?> ReadLine()
  60. {
  61. if (EndOfData)
  62. {
  63. return new Dictionary<string, object?>();
  64. }
  65. var results = Columns.ToDictionary(
  66. x => x.Key,
  67. x =>
  68. {
  69. object? result;
  70. var cell = _row.GetCell(x.Value);
  71. if(cell is null)
  72. {
  73. result = null;
  74. }
  75. else
  76. {
  77. switch(cell.GetCellType())
  78. {
  79. case CellType.Formula:
  80. result = cell.GetValue();
  81. break;
  82. case CellType.Numeric:
  83. result = cell.GetDoubleValue();
  84. break;
  85. case CellType.Date:
  86. result = cell.GetDateTimeValue();
  87. break;
  88. case CellType.String:
  89. result = cell.GetValue();
  90. break;
  91. case CellType.Boolean:
  92. result = cell.GetBoolValue();
  93. break;
  94. default:
  95. result = null;
  96. break;
  97. }
  98. }
  99. return result;
  100. });
  101. SkipLine();
  102. return results;
  103. }
  104. public bool SkipLine()
  105. {
  106. if (!EndOfData)
  107. {
  108. EndOfData = rows.MoveNext();
  109. if (!EndOfData)
  110. {
  111. _row = rows.Current;
  112. }
  113. }
  114. return EndOfData;
  115. }
  116. }
  117. }