Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions src/MiniExcel.Csv/CsvReader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -89,15 +89,17 @@ internal CsvReader(Stream stream, IMiniExcelConfiguration? configuration, bool l
continue;
}

// fields past the last header have no column name, so they are left out
var headCell = ExpandoHelper.CreateEmptyByHeaders(headRows);
var fieldCount = Math.Min(read.Length, headRows.Count);
if (_config.ReadEmptyFieldsAsDefault)
{
for (int i = 0; i <= read.Length - 1; i++)
for (int i = 0; i < fieldCount; i++)
headCell[headRows[i]] = read[i] is var value and not "" ? value : null;
}
else
{
for (int i = 0; i <= read.Length - 1; i++)
for (int i = 0; i < fieldCount; i++)
headCell[headRows[i]] = read[i];
}

Expand Down
34 changes: 34 additions & 0 deletions tests/MiniExcel.Csv.Tests/Issues/GithubIssuesTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -689,6 +689,40 @@ public void Issue979WithHeader()
Assert.Null(rows[0].C);
}

[Fact]
public async Task ExtraFieldsWithHeaderRow()
{
// fields past the last header have no column name, so they are left out like in the OpenXml reader
const string text = "A,B\n1,2,\n3,4,5,6\n";

using var path = AutoDeletingPath.Create(ExcelType.Csv);
File.WriteAllText(path.ToString(), text);

var rows = _csvImporter.Query(path.ToString(), hasHeaderRow: true).ToList();
var asyncRows = await _csvImporter.QueryAsync(path.ToString(), hasHeaderRow: true).ToListAsync();

foreach (var result in new[] { rows, asyncRows })
{
Assert.Equal(2, result.Count);
var first = (IDictionary<string, object?>)result[0];
var second = (IDictionary<string, object?>)result[1];
Assert.Equal(["A", "B"], first.Keys);
Assert.Equal("1", first["A"]);
Assert.Equal("2", first["B"]);
Assert.Equal(["A", "B"], second.Keys);
Assert.Equal("3", second["A"]);
Assert.Equal("4", second["B"]);
}

using var reader = _csvImporter.GetDataReader(path.ToString(), hasHeaderRow: true);
Assert.Equal(2, reader.FieldCount);
Assert.True(reader.Read());
Assert.Equal("2", reader.GetValue(1));
Assert.True(reader.Read());
Assert.Equal("4", reader.GetValue(1));
Assert.False(reader.Read());
}

[Fact]
public void Issue979NoHeader()
{
Expand Down
Loading