Skip to content

Commit

Permalink
Use DataFormat when reading (fixes #306)
Browse files Browse the repository at this point in the history
  • Loading branch information
mganss committed Jun 12, 2024
1 parent f635256 commit 0ea44de
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 2 deletions.
19 changes: 18 additions & 1 deletion ExcelMapper.Tests/Tests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3197,7 +3197,7 @@ record Stato
[Test]
public void StatoTest()
{
var excel = new ExcelMapper { CreateMissingHeaders = true, HeaderRow = true };
var excel = new ExcelMapper { CreateMissingHeaders = true, HeaderRow = true };

var statos = new Stato[]
{
Expand All @@ -3210,5 +3210,22 @@ public void StatoTest()

AssertEquivalent(statos, statos2);
}

record IdNumber
{
[DataFormat(1)]
public string IdNo { get; set; }
}

[Test]
public void FormatTest()
{
var rows = new ExcelMapper(@"../../../xlsx/Format.xlsx").Fetch<IdNumber>().ToList();
AssertEquivalent(rows, new[]
{
new IdNumber { IdNo = "8005065137086" },
new IdNumber { IdNo = "8402155792088" }
});
}
}
}
Binary file added ExcelMapper.Tests/xlsx/Format.xlsx
Binary file not shown.
13 changes: 12 additions & 1 deletion ExcelMapper/ExcelMapper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1495,7 +1495,18 @@ object GetCellValue(ICell cell, ColumnInfo targetColumn)
case CellType.Numeric:
if (!formulaResult && targetColumn.PropertyType == typeof(string))
{
return DataFormatter.FormatCellValue(cell);
if (targetColumn.BuiltinFormat != 0 || targetColumn.CustomFormat != null)
{
var formatIndex = targetColumn.BuiltinFormat != 0 ? targetColumn.BuiltinFormat : cell.CellStyle.DataFormat;
var formatString = targetColumn.BuiltinFormat != 0 ? BuiltinFormats.GetBuiltinFormat(targetColumn.BuiltinFormat)
: targetColumn.CustomFormat ?? cell.CellStyle.GetDataFormatString();
var formattedValue = DataFormatter.FormatRawCellContents(cell.NumericCellValue, formatIndex, formatString);
return formattedValue;
}
else
{
return DataFormatter.FormatCellValue(cell);
}
}
else if (cell.NumericCellValue <= maxDate && DateUtil.IsCellDateFormatted(cell))
{
Expand Down

0 comments on commit 0ea44de

Please sign in to comment.