NPOI 导入 Excel 日期数字值转换为 DateTime
使用 NPOI
读取 Excel 日期类型值时,获取到的数据是数字类型,需要转换为 DateTime
,这就需要使用到 DateTime.FromOADate(Double) 方法,代码示例如下:
public static DateTime? ConvertExcelDateToDateTime(this string columnValue)
{
if (string.IsNullOrWhiteSpace(columnValue))
{
return null;
}
if (DateTime.TryParse(columnValue, out DateTime date))
{
return date;
}
if (double.TryParse(columnValue, out double doubleDate))
{
return DateTime.FromOADate(doubleDate);
}
return null;
}
自定义类型实例去重
自定义类实例比较是否相同,需要重写 Equals
和 GetHastCode
方法。
假设有一个 Person 类,有 姓名、性别、年龄 三个属性,姓名、性别 决定数据的唯一性。
class Person
{
public Person(
string name,
bool gender,
int age)
{
Name = name;
Gender = gender;
Age = age;
}
public string Name { get; set; }
public bool Gender { get; set; }
public int Age { get; set; }
public override bool Equals(object obj)
{
if (obj is Person person)
{
return Name == person.Name && Gender == person.Gender;
}
return false;
}
public override int GetHashCode()
{
return $"{Name}{Gender}".GetHashCode();
}
}
现在要对用户列表去重,示例代码如下:
void Main()
{
List<Person> persons = new()
{
new Person("Marry", false, 12),
new Person("Bob", true, 16),
new Person("Marry", false, 15),
};
Console.WriteLine(persons.Distinct().Count()); // 2
}
判断一个类型是否为泛型集合
public static bool IsListType(this Type type)
{
return type.IsGenericType
&& (type.GetGenericTypeDefinition() == typeof(List<>));
}
使用场景,可以用在反射类中属性是否为泛型集合,进而遍历集合。
本文由 waynelone 创作,采用 知识共享署名4.0 国际许可协议进行许可。
本站文章除注明转载/出处外,均为本站原创或翻译,转载前请务必署名。