Allow trailing characters (m, cbm etc.) when importing numbers in Excel

This commit is contained in:
Daniel Schick 2024-08-12 11:14:46 +02:00
parent 28878447b8
commit c4cd477002

View File

@ -7,6 +7,7 @@ using Microsoft.Office.Interop.Excel;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using log4net; using log4net;
using System.Globalization; using System.Globalization;
using System.Text.RegularExpressions;
namespace ENI2.Excel namespace ENI2.Excel
{ {
@ -105,6 +106,20 @@ namespace ENI2.Excel
} }
} }
private static double? ParseAnyDouble(string val)
{
double? result = null;
if (double.TryParse(val, NumberStyles.AllowDecimalPoint | NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite,
CultureInfo.InvariantCulture, out double tmpDouble))
result = tmpDouble;
if (result == null)
{
if (double.TryParse(val, out tmpDouble)) // current language style (==GER, mit , statt .)
result = tmpDouble;
}
return result;
}
internal double? ReadNumber(string lookup) internal double? ReadNumber(string lookup)
{ {
double? result = null; double? result = null;
@ -114,15 +129,17 @@ namespace ENI2.Excel
{ {
var val = _nameDict[lookup].RefersToRange.Value; var val = _nameDict[lookup].RefersToRange.Value;
if (val is double) result = val; if (val is double) result = val;
if (val is string) if ((val is string) && (val.Length > 0))
{ {
if (double.TryParse(val, NumberStyles.AllowDecimalPoint | NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, result = ParseAnyDouble(val);
CultureInfo.InvariantCulture, out double tmpDouble))
result = tmpDouble; if(result == null)
if (result == null) {
{ Match m = Regex.Match(val, "([0-9\\.\\,]+)([a-zA-Z]*)");
if (double.TryParse(val, out tmpDouble)) // current language style (==GER, mit , statt .) if (m.Success)
result = tmpDouble; {
result = ParseAnyDouble(m.Groups[1].Value);
}
} }
} }