Skip to content

Commit

Permalink
Supports the TimeSpan type, double.NaN exports invalid values, and wh…
Browse files Browse the repository at this point in the history
…en reading, it needs to be determined whether it is a double value.
  • Loading branch information
wxn401 authored Feb 23, 2025
1 parent ca78480 commit d221726
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 3 deletions.
12 changes: 9 additions & 3 deletions src/MiniExcel/OpenXml/ExcelOpenXmlSheetReader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;
Expand Down Expand Up @@ -495,15 +496,20 @@ private void SetCellsValueAndHeaders(object cellValue, bool useHeaderRow, ref Di

if (itemValue == null)
continue;

newV = TypeHelper.TypeMapping(v, pInfo, newV, itemValue, rowIndex, startCell, configuration);
if (pInfo.ExcludeNullableType == typeof(double) && (!Regex.IsMatch(itemValue?.ToString(), "^-?\\d+(\\.\\d+)?([eE][-+]?\\d+)?$") || itemValue?.ToString().Trim().Equals("NaN") == true))//double.NaN 无效值处理
{
newV = TypeHelper.TypeMapping(v, pInfo, newV, double.NaN, rowIndex, startCell, configuration);
}
else
{
newV = TypeHelper.TypeMapping(v, pInfo, newV, itemValue, rowIndex, startCell, configuration);
}
}
}
rowIndex++;
yield return v;
}
}

private void SetSharedStrings()
{
if (_sharedStrings != null)
Expand Down
26 changes: 26 additions & 0 deletions src/MiniExcel/Utils/TypeHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,32 @@ public static bool IsNumericType(Type type, bool isNullableUnderlyingType = fals
else
throw new InvalidCastException($"{vs} can't cast to datetime");
}
else if (pInfo.ExcludeNullableType == typeof(TimeSpan))
{
if (itemValue is TimeSpan || itemValue is TimeSpan?)
{
newValue = itemValue;
pInfo.Property.SetValue(v, newValue);
return newValue;
}

var vs = itemValue?.ToString();
if (pInfo.ExcelFormat != null)
{
if (TimeSpan.TryParseExact(vs, pInfo.ExcelFormat, CultureInfo.InvariantCulture, out var _v))
{
newValue = _v;
}
}
else if (TimeSpan.TryParse(vs, _config.Culture, out var _v))
newValue = _v;
else if (TimeSpan.TryParseExact(vs, "hh\\:mm\\:ss\\.fff", CultureInfo.InvariantCulture, out var _v2))
newValue = _v2;
else if (double.TryParse(vs, NumberStyles.None, CultureInfo.InvariantCulture, out var _d))
newValue = TimeSpan.FromMilliseconds(_d);
else
throw new InvalidCastException($"{vs} can't cast to TimeSpan");
}
else if (pInfo.ExcludeNullableType == typeof(bool))
{
var vs = itemValue.ToString();
Expand Down

0 comments on commit d221726

Please sign in to comment.