Skip to content

Commit 4b7f169

Browse files
authored
Fix QueryAsDataTable can't read Excel with only header rows (#647)
* Fixed an issue with QueryAsDataTable that only header rows cannot be read correctly * handling null value
1 parent 6161e29 commit 4b7f169

File tree

1 file changed

+13
-9
lines changed

1 file changed

+13
-9
lines changed

src/MiniExcel/MiniExcel.cs

Lines changed: 13 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -184,31 +184,35 @@ public static DataTable QueryAsDataTable(this Stream stream, bool useHeaderRow =
184184

185185
var dt = new DataTable(sheetName);
186186
var first = true;
187-
var rows = ExcelReaderFactory.GetProvider(stream, ExcelTypeHelper.GetExcelType(stream, excelType), configuration).Query(useHeaderRow, sheetName, startCell);
187+
var rows = ExcelReaderFactory.GetProvider(stream, ExcelTypeHelper.GetExcelType(stream, excelType), configuration).Query(false, sheetName, startCell);
188188

189-
var keys = new List<string>();
189+
var columnDict = new Dictionary<string, string>();
190190
foreach (IDictionary<string, object> row in rows)
191191
{
192192
if (first)
193193
{
194-
foreach (var key in row.Keys)
194+
foreach (var entry in row)
195195
{
196-
if (!string.IsNullOrEmpty(key)) // avoid #298 : Column '' does not belong to table
196+
var columnName = useHeaderRow ? entry.Value?.ToString() : entry.Key;
197+
if (!string.IsNullOrWhiteSpace(columnName)) // avoid #298 : Column '' does not belong to table
197198
{
198-
var column = new DataColumn(key, typeof(object)) { Caption = key };
199+
var column = new DataColumn(columnName, typeof(object)) { Caption = columnName };
199200
dt.Columns.Add(column);
200-
keys.Add(key);
201+
columnDict.Add(entry.Key, columnName);//same column name throw exception???
201202
}
202203
}
203-
204204
dt.BeginLoadData();
205205
first = false;
206+
if (useHeaderRow)
207+
{
208+
continue;
209+
}
206210
}
207211

208212
var newRow = dt.NewRow();
209-
foreach (var key in keys)
213+
foreach (var entry in columnDict)
210214
{
211-
newRow[key] = row[key]; //TODO: optimize not using string key
215+
newRow[entry.Value] = row[entry.Key]; //TODO: optimize not using string key
212216
}
213217

214218
dt.Rows.Add(newRow);

0 commit comments

Comments
 (0)