Skip to content

Commit 0ea44de

Browse files
committed
Use DataFormat when reading (fixes #306)
1 parent f635256 commit 0ea44de

File tree

3 files changed

+30
-2
lines changed

3 files changed

+30
-2
lines changed

ExcelMapper.Tests/Tests.cs

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3197,7 +3197,7 @@ record Stato
31973197
[Test]
31983198
public void StatoTest()
31993199
{
3200-
var excel = new ExcelMapper { CreateMissingHeaders = true, HeaderRow = true };
3200+
var excel = new ExcelMapper { CreateMissingHeaders = true, HeaderRow = true };
32013201

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

32113211
AssertEquivalent(statos, statos2);
32123212
}
3213+
3214+
record IdNumber
3215+
{
3216+
[DataFormat(1)]
3217+
public string IdNo { get; set; }
3218+
}
3219+
3220+
[Test]
3221+
public void FormatTest()
3222+
{
3223+
var rows = new ExcelMapper(@"../../../xlsx/Format.xlsx").Fetch<IdNumber>().ToList();
3224+
AssertEquivalent(rows, new[]
3225+
{
3226+
new IdNumber { IdNo = "8005065137086" },
3227+
new IdNumber { IdNo = "8402155792088" }
3228+
});
3229+
}
32133230
}
32143231
}

ExcelMapper.Tests/xlsx/Format.xlsx

8.82 KB
Binary file not shown.

ExcelMapper/ExcelMapper.cs

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1495,7 +1495,18 @@ object GetCellValue(ICell cell, ColumnInfo targetColumn)
14951495
case CellType.Numeric:
14961496
if (!formulaResult && targetColumn.PropertyType == typeof(string))
14971497
{
1498-
return DataFormatter.FormatCellValue(cell);
1498+
if (targetColumn.BuiltinFormat != 0 || targetColumn.CustomFormat != null)
1499+
{
1500+
var formatIndex = targetColumn.BuiltinFormat != 0 ? targetColumn.BuiltinFormat : cell.CellStyle.DataFormat;
1501+
var formatString = targetColumn.BuiltinFormat != 0 ? BuiltinFormats.GetBuiltinFormat(targetColumn.BuiltinFormat)
1502+
: targetColumn.CustomFormat ?? cell.CellStyle.GetDataFormatString();
1503+
var formattedValue = DataFormatter.FormatRawCellContents(cell.NumericCellValue, formatIndex, formatString);
1504+
return formattedValue;
1505+
}
1506+
else
1507+
{
1508+
return DataFormatter.FormatCellValue(cell);
1509+
}
14991510
}
15001511
else if (cell.NumericCellValue <= maxDate && DateUtil.IsCellDateFormatted(cell))
15011512
{

0 commit comments

Comments
 (0)