今天写业务踩了个小坑,来记录一下。
需求是导入Excel表格到数据库,内容是一个日期的集合,导入时在cell内容转换为C#的Datetime类型时发生异常,查了下解决方法,废话不多说,上代码:
for(int rowIndex = 0;rowIndex <= sheet.LastRowNum;rowIndex ++)
{
var row = sheet.GetRow(rowIndex);
if (row == null) continue;
var cell = row.GetCell(0);
if (cell == null) continue;
//Excel的数字和日期都是numeric类型 如果按string类型处理是无法转换成日期的
if (cell.CellType != CellType.Numeric) continue;
if (!DateUtil.IsCellDateFormatted(cell)) continue;
holidayList.Add(new HolidayEntity
{
Id = string.Format("PBA{0}", Guid.NewGuid().ToString()),
Date = cell.DateCellValue
});
}
Excel的数字和日期格式的数据类型都是Numeric类型,如果按照往常直接toString()当成字符串类型处理的话,得到的结果没办法转换成C#的Date类型,所以需要判断Cell的Type,分类进行处理,我这里写的比较简单是因为业务特殊,只需要处理日期类型就可以,判断完类型后直接使用Cell的DateCellValue属性就可以获取日期了。