In ASP.NET Core-6 Web API, I am implementing Excel File upload using EPPLUS Excel Package.
I have this model:
public class LeaveApplication
{
public Guid Id { get; set; }
public string EmployeeId { get; set; }
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
public LeaveType? LeaveType { get; set; }
}
EnumList:
public class EnumList
{
public enum LeaveType : byte
{
Annual = 1,
Casual = 2,
Compassionate = 3,
Maternity = 4
}
}
So I have this method for the Excel upload.
public async Task<List<LeaveApplication>> Import(IFormFile file)
{
var list = new List<LeaveApplication>();
using (var stream = new MemoryStream())
{
await file.CopyToAsync(stream);
using (var package = new ExcelPackage(stream))
{
ExcelWorksheet worksheet = package.Workbook.Worksheets[0];
var rowcount = worksheet.Dimension.Rows;
var colcount = worksheet.Dimension.Columns;
for (int row = 2; row < rowcount; row )
{
list.Add(new LeaveApplication {
EmployeeId = worksheet.Cells[row,1].Value.ToString().Trim(),
StartDate = DateTime.Parse(worksheet.Cells[row, 2].Value.ToString()),
EndDate = DateTime.Parse(worksheet.Cells[row, 3].Value.ToString()),
LeaveType = byte.Parse(worksheet.Cells[row, 4].Value.ToString())
});
}
}
}
_dbContext.LeaveApplications.AddRange(list);
await _dbContext.SaveChangesAsync();
return list;
}
I got this error:
Cannot implicitly convert type 'byte' to 'EnumList.LeaveType?'. An explicit conversion exists (are you missing a cast?)
Then this line of code is highlighted:
LeaveType = byte.Parse(worksheet.Cells[row, 4].Value.ToString())
How do I get this resolved?
Thanks
CodePudding user response:
Explicit cast from byte
to EnumList.LeaveType
.
LeaveType = String.IsNullOrEmpty(worksheet.Cells[row, 4].Value.ToString())
? (EnumList.LeaveType?)null
: (EnumList.LeaveType)byte.Parse(worksheet.Cells[row, 4].Value.ToString())
Or you can work with parsing from string
to EnumList.LeaveType
:
LeaveType = String.IsNullOrEmpty(worksheet.Cells[row, 4].Value.ToString())
? (EnumList.LeaveType?)null
: Enum.Parse(typeof(EnumList.LeaveType), worksheet.Cells[row, 4].Value.ToString())
Will recommend using Enum.TryParse()
to avoid the exception due to an invalid value for the enum
.