Home > Enterprise >  Asp.Net Core - Control empty Excel cells to enter information in the database?
Asp.Net Core - Control empty Excel cells to enter information in the database?

Time:02-23

I use the EPPlus plugin to get information from Excel.The following code works perfectly, but how to control it when it gets an error after it reaches the empty Excel cell?

 public async Task<IActionResult> AddExcellHorse(IFormFile ExcelFile)
    {
        using (var stream = new MemoryStream())
        {
            await ExcelFile.CopyToAsync(stream);

            using (var package = new ExcelPackage(stream))
            {
                ExcelWorksheet worksheet = package.Workbook.Worksheets[0];
                var rowCount = worksheet.Dimension.Rows;

                for (int i = 2; i <= rowCount; i  )
                {
                    AddExcelHorse viewModel = new AddExcelHorse()
                    {
                        MicrochipCode = worksheet.Cells[i, 1].Value.ToString().Trim(),                           
                        EnHorseName = worksheet.Cells[i, 2].Value.ToString().Trim(),                           
                        EnFatherHorseName = worksheet.Cells[i, 3].Value.ToString().Trim(),                           
                        EnMotherHorseName = worksheet.Cells[i, 4].Value.ToString().Trim(),                   
                    };
                    if (viewModel.MicrochipCode != null)
                    {
                        if (!_admin.ChechMicrochip(viewModel.MicrochipCode))
                        {
                            _admin.AddExcelHorse(viewModel);
                        }
                    }                    }
                return RedirectToAction(nameof(Index));
            }
        }
    }

CodePudding user response:

I assume you run into a null reference exception, because the cell value is null, then .ToString() cannot be called.

You could wrap everything in a seperate if-block:

if(worksheet.Cells[i, 1].Value != null) 
{
    MicrochipCode = worksheet.Cells[i, 1].Value.ToString().Trim(), 
}

or you use the null propagation:

MicrochipCode = worksheet.Cells[i, 1].Value?.ToString().Trim(), 

//or with default value, if null is not good enough.
MicrochipCode = worksheet.Cells[i, 1].Value?.ToString().Trim() ?? String.Empty, 
  • Related