Skip to content

Commit d221726

Browse files
authored
Supports the TimeSpan type, double.NaN exports invalid values, and when reading, it needs to be determined whether it is a double value.
1 parent ca78480 commit d221726

File tree

2 files changed

+35
-3
lines changed

2 files changed

+35
-3
lines changed

src/MiniExcel/OpenXml/ExcelOpenXmlSheetReader.cs

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
using System.IO;
88
using System.IO.Compression;
99
using System.Linq;
10+
using System.Text.RegularExpressions;
1011
using System.Threading;
1112
using System.Threading.Tasks;
1213
using System.Xml;
@@ -495,15 +496,20 @@ private void SetCellsValueAndHeaders(object cellValue, bool useHeaderRow, ref Di
495496

496497
if (itemValue == null)
497498
continue;
498-
499-
newV = TypeHelper.TypeMapping(v, pInfo, newV, itemValue, rowIndex, startCell, configuration);
499+
if (pInfo.ExcludeNullableType == typeof(double) && (!Regex.IsMatch(itemValue?.ToString(), "^-?\\d+(\\.\\d+)?([eE][-+]?\\d+)?$") || itemValue?.ToString().Trim().Equals("NaN") == true))//double.NaN 无效值处理
500+
{
501+
newV = TypeHelper.TypeMapping(v, pInfo, newV, double.NaN, rowIndex, startCell, configuration);
502+
}
503+
else
504+
{
505+
newV = TypeHelper.TypeMapping(v, pInfo, newV, itemValue, rowIndex, startCell, configuration);
506+
}
500507
}
501508
}
502509
rowIndex++;
503510
yield return v;
504511
}
505512
}
506-
507513
private void SetSharedStrings()
508514
{
509515
if (_sharedStrings != null)

src/MiniExcel/Utils/TypeHelper.cs

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -129,6 +129,32 @@ public static bool IsNumericType(Type type, bool isNullableUnderlyingType = fals
129129
else
130130
throw new InvalidCastException($"{vs} can't cast to datetime");
131131
}
132+
else if (pInfo.ExcludeNullableType == typeof(TimeSpan))
133+
{
134+
if (itemValue is TimeSpan || itemValue is TimeSpan?)
135+
{
136+
newValue = itemValue;
137+
pInfo.Property.SetValue(v, newValue);
138+
return newValue;
139+
}
140+
141+
var vs = itemValue?.ToString();
142+
if (pInfo.ExcelFormat != null)
143+
{
144+
if (TimeSpan.TryParseExact(vs, pInfo.ExcelFormat, CultureInfo.InvariantCulture, out var _v))
145+
{
146+
newValue = _v;
147+
}
148+
}
149+
else if (TimeSpan.TryParse(vs, _config.Culture, out var _v))
150+
newValue = _v;
151+
else if (TimeSpan.TryParseExact(vs, "hh\\:mm\\:ss\\.fff", CultureInfo.InvariantCulture, out var _v2))
152+
newValue = _v2;
153+
else if (double.TryParse(vs, NumberStyles.None, CultureInfo.InvariantCulture, out var _d))
154+
newValue = TimeSpan.FromMilliseconds(_d);
155+
else
156+
throw new InvalidCastException($"{vs} can't cast to TimeSpan");
157+
}
132158
else if (pInfo.ExcludeNullableType == typeof(bool))
133159
{
134160
var vs = itemValue.ToString();

0 commit comments

Comments
 (0)