TropicalViking
TropicalViking

Reputation: 425

C# how to handle null values in a list when importing from an excel worksheet

I am importing a worksheet from excel into a sql server localdb using C# and Excelpackage. I have of course got null values in the worksheet, for example on strings and doubles. On doubles I have got normally no issues. How to handle in advance that if there is a null value on workSheet.Cells[i, 1].Value.ToString(), then insert null into the database context class ?

 using (ExcelPackage package = new ExcelPackage(file))
            {
                ExcelWorksheet workSheet = package.Workbook.Worksheets["Table_Methode"];
                int totalRows = workSheet.Dimension.Rows;

                List<Methode> methodesList = new List<Methode>();

                for (int i = 2; i <= totalRows; i++)
                {
                    methodesList.Add(new Methode
                    {
                        NomMethode = workSheet.Cells[i, 1].Value.ToString() == null ? "":workSheet.Cells[i, 1].Value.ToString()
                    });
                }
                _context.Methode.AddRange(methodesList);
                _context.SaveChanges();
                return methodesList;
            }

Upvotes: 1

Views: 1593

Answers (1)

Jon
Jon

Reputation: 3255

I would just check for null and empty strings before adding:

using (ExcelPackage package = new ExcelPackage(file))
{
    ExcelWorksheet workSheet = package.Workbook.Worksheets["Table_Methode"];
    int totalRows = workSheet.Dimension.Rows;

    List<Methode> methodesList = new List<Methode>();

    for (int i = 2; i <= totalRows; i++)
    {
        if (workSheet.Cells[i, 1].Value != null && workSheet.Cells[i, 1].Value != String.Empty)
        {
            methodesList.Add(new Methode
            {
                NomMethode = workSheet.Cells[i, 1].Value.ToString();
            });
        }
    }

    _context.Methode.AddRange(methodesList);
    _context.SaveChanges();
    return methodesList;
}

Upvotes: 1

Related Questions