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
18 changes: 10 additions & 8 deletions src/EPPlus/LoadFunctions/LoadFromTextBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -62,16 +62,18 @@ protected bool IsEOL(string text, int ix, string eol)

protected object ConvertData(T Format, eDataTypes[] dataType, string v, int col, bool isText)
{
if (isText && (dataType == null || dataType.Length < col))
{
return string.IsNullOrEmpty(v) ? null : v;
}
else
bool isOutOfBounds = dataType == null || col >= dataType.Length;

if (isOutOfBounds)
{
if(dataType == null || dataType.Length < col)
return ConvertData(Format, eDataTypes.Unknown, v, col, isText);
return ConvertData(Format, dataType[col], v, col, isText);
if (isText)
{
return string.IsNullOrEmpty(v) ? null : v;
}
return ConvertData(Format, eDataTypes.Unknown, v, col, isText);
}

return ConvertData(Format, dataType[col], v, col, isText);
}

protected object ConvertData(T Format, eDataTypes? dataType, string v, int col, bool isText)
Expand Down
16 changes: 16 additions & 0 deletions src/EPPlusTest/LoadFunctions/LoadFromTextTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -467,5 +467,21 @@ public void ReadFixedTextFile3()
}
}

[TestMethod]
public void ShouldLoadCsvFormatWithTrailingColumns()
{
// This test verifies that importing a text/CSV file with more columns than specified in DataTypes does not crash.
// Previously, an off-by-one bounds check (dataType.Length < col) allowed the loop to attempt accessing dataType[col]
// when 'col' was equal to 'dataType.Length', resulting in a System.IndexOutOfRangeException.
// With the fix (col >= dataType.Length), trailing columns beyond the DataTypes array are gracefully imported as Unknown (General).
AddLine("a;2;extra");
_format.Delimiter = ';';
_format.DataTypes = new eDataTypes[] { eDataTypes.String, eDataTypes.Number };
_worksheet.Cells["A1"].LoadFromText(_lines.ToString(), _format);
Assert.AreEqual("a", _worksheet.Cells["A1"].Value);
Assert.AreEqual(2d, _worksheet.Cells["B1"].Value);
Assert.AreEqual("extra", _worksheet.Cells["C1"].Value);
}

}
}
Loading