ExcelFileReader.cs 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121
  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. using System.Diagnostics.CodeAnalysis;
  13. namespace InABox.Scripting
  14. {
  15. public class ExcelFileReader : ITabularFileReader
  16. {
  17. private IEnumerator<IRow> rows;
  18. public Dictionary<string, int> Columns { get; set; }
  19. [MemberNotNullWhen(false, nameof(_row))]
  20. public bool EndOfData { get; private set; }
  21. private IRow? _row;
  22. public ExcelFileReader(Stream stream)
  23. {
  24. rows = new Spreadsheet(stream).GetSheet(0).RowEnumerator();
  25. Columns = new Dictionary<string, int>();
  26. SkipLine();
  27. }
  28. public IList<string> ReadLineValues()
  29. {
  30. var results = new List<string>();
  31. if (!EndOfData)
  32. {
  33. foreach (var cell in _row.Cells())
  34. {
  35. results.Add(cell.GetValue());
  36. }
  37. SkipLine();
  38. }
  39. return results;
  40. }
  41. public bool ReadHeader()
  42. {
  43. Columns.Clear();
  44. if (EndOfData)
  45. {
  46. return false;
  47. }
  48. int i = 0;
  49. foreach(var cell in _row.Cells())
  50. {
  51. var column = cell.GetValue();
  52. if (!column.IsNullOrWhiteSpace())
  53. {
  54. Columns.Add(column, i);
  55. }
  56. ++i;
  57. }
  58. SkipLine();
  59. return true;
  60. }
  61. public Dictionary<string, object?> ReadLine()
  62. {
  63. if (EndOfData)
  64. {
  65. return new Dictionary<string, object?>();
  66. }
  67. var results = Columns.ToDictionary(
  68. x => x.Key,
  69. x =>
  70. {
  71. object? result;
  72. var cell = _row.GetCell(x.Value);
  73. if(cell is null)
  74. {
  75. result = null;
  76. }
  77. else
  78. {
  79. result = cell.GetCellType() switch
  80. {
  81. CellType.Formula => cell.GetValue(),
  82. CellType.Numeric => cell.GetDoubleValue(),
  83. CellType.Date => cell.GetDateTimeValue(),
  84. CellType.String => cell.GetValue(),
  85. CellType.Boolean => cell.GetBoolValue(),
  86. _ => null,
  87. };
  88. }
  89. return result;
  90. });
  91. SkipLine();
  92. return results;
  93. }
  94. public bool SkipLine()
  95. {
  96. if (!EndOfData)
  97. {
  98. EndOfData = !rows.MoveNext();
  99. if (!EndOfData)
  100. {
  101. _row = rows.Current;
  102. }
  103. }
  104. return EndOfData;
  105. }
  106. }
  107. }