-
Notifications
You must be signed in to change notification settings - Fork 189
Expand file tree
/
Copy pathExcelQuery.cs
More file actions
330 lines (293 loc) · 12 KB
/
ExcelQuery.cs
File metadata and controls
330 lines (293 loc) · 12 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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
///////////////////////////////////////////////////////////////////////////////
///
/// ExcelQuery.cs
///
/// (c)2014 Kim, Hyoun Woo
///
///////////////////////////////////////////////////////////////////////////////
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.IO;
using System;
using System.Linq;
using System.ComponentModel;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
namespace UnityQuickSheet
{
/// <summary>
/// Query each of cell data from the given excel sheet and deserialize it to the ScriptableObject's data array.
/// </summary>
public class ExcelQuery
{
private readonly IWorkbook workbook = null;
private readonly ISheet sheet = null;
private string filepath = string.Empty;
/// <summary>
/// Constructor.
/// </summary>
public ExcelQuery(string path, string sheetName = "")
{
try
{
using (FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
string extension = GetSuffix(path);
if (extension == "xls")
workbook = new HSSFWorkbook(fileStream);
else if (extension == "xlsx")
{
#if UNITY_EDITOR_OSX
throw new Exception("xlsx is not supported on OSX.");
#else
workbook = new XSSFWorkbook(fileStream);
#endif
}
else
{
throw new Exception("Wrong file.");
}
//NOTE: An empty sheetName can be available. Nothing to do with an empty sheetname.
if (!string.IsNullOrEmpty(sheetName))
{
sheet = workbook.GetSheet(sheetName);
if (sheet == null)
Debug.LogErrorFormat("Cannot find sheet '{0}'.", sheetName);
}
this.filepath = path;
}
}
catch (Exception e)
{
Debug.LogError(e.Message);
}
}
/// <summary>
/// Determine whether the excel file is successfully read in or not.
/// </summary>
public bool IsValid()
{
if (this.workbook != null && this.sheet != null)
return true;
return false;
}
/// <summary>
/// Retrieves file extension only from the given file path.
/// </summary>
static string GetSuffix(string path)
{
string ext = Path.GetExtension(path);
string[] arg = ext.Split(new char[] { '.' });
return arg[1];
}
string GetHeaderColumnName(int cellnum)
{
ICell headerCell = sheet.GetRow(0).GetCell(cellnum);
if (headerCell != null)
return headerCell.StringCellValue;
return string.Empty;
}
/// <summary>
/// Deserialize all the cell of the given sheet.
///
/// NOTE:
/// The first row of a sheet is header column which is not the actual value
/// so it skips when it deserializes.
/// </summary>
public List<T> Deserialize<T>(int start = 1)
{
var t = typeof(T);
PropertyInfo[] p = t.GetProperties();
var result = new List<T>();
int current = 0;
foreach (IRow row in sheet)
{
if (current < start)
{
current++; // skip header column.
continue;
}
var item = (T)Activator.CreateInstance(t);
for (var i = 0; i < p.Length; i++)
{
ICell cell = row.GetCell(i);
if (cell == null) // skip empty cell
continue;
var property = p[i];
if (property.CanWrite)
{
try
{
var value = ConvertFrom(cell, property.PropertyType);
property.SetValue(item, value, null);
}
catch (Exception e)
{
string pos = string.Format("Row[{0}], Cell[{1}]", (current).ToString(), GetHeaderColumnName(i));
Debug.LogError(string.Format("Excel File {0} Deserialize Exception: {1} at {2}", this.filepath, e.Message, pos));
}
}
}
result.Add(item);
current++;
}
return result;
}
/// <summary>
/// Retrieves all sheet names.
/// </summary>
public string[] GetSheetNames()
{
List<string> sheetList = new List<string>();
if (this.workbook != null)
{
int numSheets = this.workbook.NumberOfSheets;
for (int i = 0; i < numSheets; i++)
{
sheetList.Add(this.workbook.GetSheetName(i));
}
}
else
Debug.LogError("Workbook is null. Did you forget to import excel file first?");
return (sheetList.Count > 0) ? sheetList.ToArray() : null;
}
/// <summary>
/// Retrieves all first columns(aka. header column) which are needed to determine each type of a cell.
/// </summary>
public string[] GetTitle(int start, ref string error)
{
if (sheet == null)
{
error = @"Sheet is null";
return null;
}
List<string> result = new List<string>();
IRow title = sheet.GetRow(start);
if (title != null)
{
for (int i = 0; i < title.LastCellNum; i++)
{
var cell = title.GetCell(i);
if (cell == null)
{
// null or empty column is found. Note column index starts from 0.
Debug.LogWarningFormat("Null or empty column is found at {0}.\n", i);
continue;
}
string value = cell.StringCellValue;
if (string.IsNullOrEmpty(value))
{
// null or empty column is found. Note column index starts from 0.
Debug.LogWarningFormat("Null or empty column is found at {0}.The celltype of {0} is '{1}' type.\n", i, title.GetCell(i).CellType);
}
else
{
// column header is not an empty string, we check its validation later.
result.Add(value);
}
}
return result.ToArray();
}
error = string.Format(@"Empty row at {0}", start);
return null;
}
/// <summary>
/// Convert type of cell value to its predefined type which is specified in the sheet's ScriptMachine setting file.
/// </summary>
protected object ConvertFrom(ICell cell, Type t)
{
object value = null;
if (t == typeof(float) || t == typeof(double) || t == typeof(short) || t == typeof(int) || t == typeof(long))
{
if (cell.CellType == NPOI.SS.UserModel.CellType.Numeric)
{
value = cell.NumericCellValue;
}
else if (cell.CellType == NPOI.SS.UserModel.CellType.String)
{
//Get correct numeric value even the cell is string type but defined with a numeric type in a data class.
if (t == typeof(float))
value = Convert.ToSingle(cell.StringCellValue);
if (t == typeof(double))
value = Convert.ToDouble(cell.StringCellValue);
if (t == typeof(short))
value = Convert.ToInt16(cell.StringCellValue);
if (t == typeof(int))
value = Convert.ToInt32(cell.StringCellValue);
if (t == typeof(long))
value = Convert.ToInt64(cell.StringCellValue);
}
else if (cell.CellType == NPOI.SS.UserModel.CellType.Formula)
{
// Get value even if cell is a formula
if (t == typeof(float))
value = Convert.ToSingle(cell.NumericCellValue);
if (t == typeof(double))
value = Convert.ToDouble(cell.NumericCellValue);
if (t == typeof(short))
value = Convert.ToInt16(cell.NumericCellValue);
if (t == typeof(int))
value = Convert.ToInt32(cell.NumericCellValue);
if (t == typeof(long))
value = Convert.ToInt64(cell.NumericCellValue);
}
}
else if (t == typeof(string) || t.IsArray)
{
// HACK: handles the case that a cell contains numeric value
// but a member field in a data class is defined as string type.
// e.g. string s = "123"
if (cell.CellType == NPOI.SS.UserModel.CellType.Numeric)
value = cell.NumericCellValue;
else
value = cell.StringCellValue;
}
else if (t == typeof(bool))
value = cell.BooleanCellValue;
if (t.IsGenericType && t.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
{
var nc = new NullableConverter(t);
return nc.ConvertFrom(value);
}
if (t.IsEnum)
{
// for enum type, first get value by string then convert it to enum.
value = cell.StringCellValue;
return Enum.Parse(t, value.ToString(), true);
}
else if (t.IsArray)
{
if (t.GetElementType() == typeof(float))
return ConvertExt.ToSingleArray((string)value);
if (t.GetElementType() == typeof(double))
return ConvertExt.ToDoubleArray((string)value);
if (t.GetElementType() == typeof(short))
return ConvertExt.ToInt16Array((string)value);
if (t.GetElementType() == typeof(int))
return ConvertExt.ToInt32Array((string)value);
if (t.GetElementType() == typeof(long))
return ConvertExt.ToInt64Array((string)value);
if (t.GetElementType() == typeof(string))
return ConvertExt.ToStringArray((string)value);
if (t.GetElementType().IsEnum)
{
var stringValue = cell.StringCellValue.ToString();
var splitValues = stringValue.Split(',');
var enumArray = Array.CreateInstance(t.GetElementType(), splitValues.Length);
for (int i = 0; i < splitValues.Length; ++i)
{
string splitValue = splitValues[i];
var enumValue = Enum.Parse(t.GetElementType(), splitValue, true);
enumArray.SetValue(enumValue, i);
}
return enumArray;
}
}
// for all other types, convert its corresponding type.
return Convert.ChangeType(value, t);
}
}
}