7 次代码提交 9a903598e9 ... 87536f1fc4

作者 SHA1 备注 提交日期
  Piotr Czajkowski 87536f1fc4 Last touch 10 月之前
  Piotr Czajkowski eb8d299329 Additional explanation 10 月之前
  Piotr Czajkowski 6f14a6ff4c Added ReadAdditionalTypesNullable 10 月之前
  Piotr Czajkowski d74fc78bec Let's handle non-nullable as well 10 月之前
  Piotr Czajkowski 672d4bd705 Cleaner 10 月之前
  Piotr Czajkowski 5a797c78d5 Version bump 10 月之前
  Piotr Czajkowski ac7cb1381b Able to read additional types 10 月之前

+ 2 - 2
ExcelORM/ExcelORM/ExcelORM.csproj

@@ -4,7 +4,7 @@
         <TargetFramework>net8.0</TargetFramework>
         <ImplicitUsings>enable</ImplicitUsings>
         <Nullable>enable</Nullable>
-        <Version>2.6.0</Version>
+        <Version>2.7.0</Version>
         <PackageProjectUrl>https://git.liox.eu/pczajkowski/ExcelORM</PackageProjectUrl>
         <RepositoryUrl>https://github.com/pczajkowski/ExcelORM</RepositoryUrl>
         <GeneratePackageOnBuild>true</GeneratePackageOnBuild>
@@ -14,7 +14,7 @@
 	<Authors>Piotr Czajkowski</Authors>
 	<Description>Simple library to read/write C# objects from/to Excel files. </Description>
 	<RepositoryType>GitHub</RepositoryType>
-	<PackageReleaseNotes>Able to append starting from given row.</PackageReleaseNotes>
+	<PackageReleaseNotes>Able to read enums and Guids.</PackageReleaseNotes>
     </PropertyGroup>
 
     <ItemGroup>

+ 32 - 3
ExcelORM/ExcelORM/TypeExtensions.cs

@@ -6,15 +6,44 @@ namespace ExcelORM;
 
 public static class TypeExtensions
 {
+    private static object? GetAdditionalTypeFromText(XLCellValue value, PropertyInfo? property = null)
+    {
+        if (property == null) return value.GetText();
+        
+        if (property.PropertyType == typeof(Guid) || property.PropertyType == typeof(Guid?))
+        {
+            if (Guid.TryParse(value.GetText(), out var guid))
+                return guid;
+
+            if (property.PropertyType == typeof(Guid?)) return null;
+            return Guid.Empty;
+        }
+
+        if (property.PropertyType.IsEnum)
+        {
+            return Enum.TryParse(property.PropertyType, value.GetText(), true, out var enumValue)
+                ? enumValue : Enum.GetValues(property.PropertyType).GetValue(0);
+        }
+
+        var nullableUnderlyingType = Nullable.GetUnderlyingType(property.PropertyType);
+        if (nullableUnderlyingType is { IsEnum: true })
+        {
+            return Enum.TryParse(nullableUnderlyingType, value.GetText(), true, out var enumValue)
+                ? enumValue : null;
+        }
+        
+        return value.GetText(); 
+    }
+    
     // Borrowed from https://github.com/ClosedXML/ClosedXML/blob/develop/ClosedXML/Excel/XLCellValue.cs#L361
-    public static object? ToObject(this XLCellValue value)
+    public static object? ToObject(this XLCellValue value, PropertyInfo? property = null)
     {
         return value.Type switch
         {
             XLDataType.Blank => null,
             XLDataType.Boolean => value.GetBoolean(),
             XLDataType.Number => value.GetNumber(),
-            XLDataType.Text => value.GetText(),
+            XLDataType.Text => GetAdditionalTypeFromText(value, property),
             XLDataType.Error => value.GetError(),
             XLDataType.DateTime => value.GetDateTime(),
             XLDataType.TimeSpan => value.GetTimeSpan(),
@@ -38,7 +67,7 @@ public static class TypeExtensions
 
     public static void SetPropertyValue<T>(this T currentObject, PropertyInfo property, XLCellValue value)
     {
-        var valueToSet = value.ToObject();
+        var valueToSet = value.ToObject(property);
         if (valueToSet == null) return;
 
         try

+ 3 - 0
ExcelORM/ExcelORMTests/ExcelORMTests.csproj

@@ -59,6 +59,9 @@
       <None Update="testFiles\forAppendWithRubbish.xlsx">
         <CopyToOutputDirectory>Always</CopyToOutputDirectory>
       </None>
+      <None Update="testFiles\additionalTypes.xlsx">
+        <CopyToOutputDirectory>Always</CopyToOutputDirectory>
+      </None>
     </ItemGroup>
 
     <ItemGroup>

+ 17 - 0
ExcelORM/ExcelORMTests/ReaderTests.cs

@@ -12,6 +12,7 @@ public class ReaderTests
     private const string DifferentTypesFile = "testFiles/differentTypes.xlsx";
     private const string WithFormulaFile = "testFiles/withFormula.xlsx";
     private const string BadDate = "testFiles/badDate.xlsx";
+    private const string AdditionalTypes = "testFiles/additionalTypes.xlsx";
     
     [Fact]
     public void Read()
@@ -118,4 +119,20 @@ public class ReaderTests
         var exception = Assert.Throws<ArgumentException>(() => reader.Read<TestTypes>().ToArray());
         Assert.Contains("Location", exception.Message);
     }
+    
+    [Fact]
+    public void ReadAdditionalTypes()
+    {
+        using var reader = new ExcelReader(AdditionalTypes);
+        var results = reader.Read<TestAdditionalTypes>().ToArray();
+        Assert.NotEmpty(results);
+    }
+    
+    [Fact]
+    public void ReadAdditionalTypesNullable()
+    {
+        using var reader = new ExcelReader(AdditionalTypes);
+        var results = reader.Read<TestAdditionalTypesNullable>().ToArray();
+        Assert.NotEmpty(results);
+    }
 }

+ 7 - 0
ExcelORM/ExcelORMTests/TestAdditionalTypes.cs

@@ -0,0 +1,7 @@
+namespace ExcelORMTests;
+
+public record TestAdditionalTypes
+{
+    public TestEnum MyEnum {get; set;}
+    public Guid MyGuid {get; set;}
+}

+ 7 - 0
ExcelORM/ExcelORMTests/TestAdditionalTypesNullable.cs

@@ -0,0 +1,7 @@
+namespace ExcelORMTests;
+
+public record TestAdditionalTypesNullable
+{
+    public TestEnum? MyEnum {get; set;}
+    public Guid? MyGuid {get; set;}
+}

+ 7 - 0
ExcelORM/ExcelORMTests/TestEnum.cs

@@ -0,0 +1,7 @@
+namespace ExcelORMTests;
+
+public enum TestEnum
+{
+    First,
+    Second,
+}

二进制
ExcelORM/ExcelORMTests/testFiles/additionalTypes.xlsx


+ 4 - 0
README.md

@@ -15,6 +15,10 @@ It currently supports properties of types as supported by ClosedXML, so:
 - DateTime
 - TimeSpan
 
+Additionally, it supports:
+- Guid (if not a valid Guid and non-nullable then empty Guid will be returned)
+- enum (if not a valid enum value and non-nullable then default value will be returned)
+
 And their nullable variants.
 
 As always, feel free to use it however you desire. But I provide you with no guarantee whatsoever. Enjoy!

+ 6 - 5
versions.md

@@ -2,8 +2,9 @@
 
 | Version | Description |
 | ----------- | ----------- |
-| 2.0.0 | I've added ability to read data dynamically without a need to create a special type. Useful when you need to read/write some not so organized data.|
-| 2.2.0 | I've added support for formulas, but as this library is based on ClosedXML it has its limitations, as per [Evaluating Formulas](https://github.com/closedxml/closedxml/wiki/Evaluating-Formulas): *Not all formulas are included and you'll probably get a nasty error if the formula isn't supported or if there's an error in the formula. Please test your formulas before going to production.*|
-| 2.3.0 | I've added support for hyperlinks and improved appending to the existing files.|
-| 2.5.0 | I've added Location to ArgumentException Message in ExcelReader. It'll show address of affected cell and the worksheet's name.|
-| 2.6.0 | I've added support for appending starting from given row.|
+| 2.0.0 | Added ability to read data dynamically without a need to create a special type. Useful when you need to read/write some not so organized data.|
+| 2.2.0 | Added support for formulas, but as this library is based on ClosedXML it has its limitations, as per [Evaluating Formulas](https://github.com/closedxml/closedxml/wiki/Evaluating-Formulas): *Not all formulas are included and you'll probably get a nasty error if the formula isn't supported or if there's an error in the formula. Please test your formulas before going to production.*|
+| 2.3.0 | Added support for hyperlinks and improved appending to the existing files.|
+| 2.5.0 | Added Location to ArgumentException Message in ExcelReader. It'll show address of affected cell and the worksheet's name.|
+| 2.6.0 | Added support for appending starting from given row.|
+| 2.7.0 | Added support for reading properties of type Guid and enum.|