-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathExcelReader.cs
More file actions
128 lines (96 loc) · 3.44 KB
/
ExcelReader.cs
File metadata and controls
128 lines (96 loc) · 3.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Office.Interop.Excel;
using System.Runtime.InteropServices;
namespace Excell
{
class ExcelReader
{
private Application xlApp = new Application();
private Workbook xlWorkbook;
private Worksheet xlWorksheet;
private Range usedRange;
public int rowsCount;
List<string> headers = new List<string>();
private List<string> getRow(int rowNumber)
{
List<string> row = new List<string>();
if (rowNumber > 0)
{
for (int i = 1; i <= usedRange.Columns.Count; i++)
{
if (usedRange.Cells[rowNumber, i] != null && usedRange.Cells[rowNumber, i].Value2 != null)
{
row.Add(usedRange.Cells[rowNumber, i].Value2.ToString());
}
}
}
return row;
}
private List<string> getHeaders()
{
return getRow(1);
}
public bool IsRowEmpty(int rowNumber)
{
List<string> row = getRow(rowNumber);
if(row.Count != 0)
{
return false;
} else {
return true;
}
}
public ExcelReader(string filePath)
{
this.xlWorkbook = xlApp.Workbooks.Open(filePath);
}
public void LoadWorkSheet(int workSheetNumber)
{
this.xlWorksheet = xlWorkbook.Sheets[workSheetNumber];
this.usedRange = this.xlWorksheet.UsedRange;
this.rowsCount = this.usedRange.Rows.Count;
headers = getHeaders();
}
public List<string> GetWorkSheetsNames() {
List<string> workSheetsNames = new List<string>();
for(int i = 1; i <= this.xlWorkbook.Worksheets.Count; i++) {
Worksheet currentWorkSheet = this.xlWorkbook.Worksheets[i];
workSheetsNames.Add(currentWorkSheet.Name);
}
return workSheetsNames;
}
public List<Field> getRowFields(int row)
{
List<Field> list = new List<Field>();
for (int i = 2; i < headers.Count; i++)
{
if (usedRange.Cells[row, i + 1] != null && usedRange.Cells[row, i + 1].Value2 != null)
{
Field field = new Field(usedRange.Cells[row, 1].Value2 != null ? usedRange.Cells[row, 1].Value2.ToString() : "" ,
usedRange.Cells[row, 2].Value2 != null ? usedRange.Cells[row, 2].Value2.ToString() : "",
headers[i],
usedRange.Cells[row, i + 1].Value2.ToString());
list.Add(field);
}
}
return list;
}
private void CleanMemory()
{
GC.Collect();
GC.WaitForPendingFinalizers();
}
public void Release()
{
CleanMemory();
Marshal.ReleaseComObject(usedRange);
Marshal.ReleaseComObject(xlWorksheet);
xlWorkbook.Close();
Marshal.ReleaseComObject(xlWorkbook);
xlApp.Quit();
Marshal.ReleaseComObject(xlApp);
}
}
}