diff --git a/src/EPPlus/LoadFunctions/LoadFromTextBase.cs b/src/EPPlus/LoadFunctions/LoadFromTextBase.cs index a61614e06d..2a1d2e719b 100644 --- a/src/EPPlus/LoadFunctions/LoadFromTextBase.cs +++ b/src/EPPlus/LoadFunctions/LoadFromTextBase.cs @@ -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) diff --git a/src/EPPlusTest/LoadFunctions/LoadFromTextTests.cs b/src/EPPlusTest/LoadFunctions/LoadFromTextTests.cs index ce444fed02..c49ab6abe7 100644 --- a/src/EPPlusTest/LoadFunctions/LoadFromTextTests.cs +++ b/src/EPPlusTest/LoadFunctions/LoadFromTextTests.cs @@ -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); + } + } }