1

我正在使用 C# 和 Excelpackage 将工作表从 excel 导入 sql server localdb。我当然在工作表中有空值,例如字符串和双打。在双打上,我通常没有问题。如果workSheet.Cells[i, 1].Value.ToString()上有空值,如何提前处理,然后在数据库上下文类中插入空值?

 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;
            }
4

1 回答 1

1

我会在添加之前检查空字符串和空字符串:

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;
}
于 2019-09-13T14:24:16.043 回答