简体   繁体   English

如何使用 EPPLUS 读取导入的 excel 文件?

[英]How to read import excel file with EPPLUS?

    private readonly ILogger<HomeController> _logger;

    public HomeController(ILogger<HomeController> logger, ApplicationDbContext context)
    {
        _logger = logger;
        _context = context;
    }

    public IActionResult Index()
    {
        return View();
    }

    ApplicationDbContext _context;
    
    public List<Contact>Import (string fileName)
    {

        var FilePath = $"{Directory.GetCurrentDirectory()}{@""}" + "\\" + fileName;
        FileInfo fileInfo = new FileInfo(FilePath);
        ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
        using (ExcelPackage package = new ExcelPackage(fileInfo))
        {
            ExcelWorksheet worksheet = package.Workbook.Worksheets.FirstOrDefault();
          
            int rowCount = worksheet.Dimension.End.Row;
            for (int row = 2; row <= rowCount; row++)
            {
                Contact con = new Contact();
             
                    if (row == 1) con.Libelle = worksheet.Cells[row, row].Value.ToString();
                    else if (row == 2) con.Id = (int)worksheet.Cells[row, row].Value;

               
                _context.Add(con);
                _context.SaveChanges(); 
            }
        }
        return _context.Contacts.ToList();
    }

I'm trying to read excel file with EPPLUS but i have one excepton, it is saying that System.NullReferenceException : 'Object reference not set to an instance of an object.'我正在尝试使用 EPPLUS 读取 excel 文件,但我有一个异常,它说 System.NullReferenceException:'对象引用未设置为对象的实例。 worksheet a été null.工作表 a été null。

I will suggest You adapt 'defensive programming' paradigm to Your approach in these cases.在这些情况下,我会建议您将“防御性编程”范式适应您的方法。 Specifically meaning do not write code that acts on assuming something else goes well without checking.具体意思是不要编写代码,假设其他事情顺利进行而不进行检查。 When you do so I believe the problem will show.当你这样做时,我相信问题会出现。

Of cause community cannot help you if the problem is with the excel sheet, unless you can supply it - but I do see some helpfull suggestions as to coding style which i belive can help You solve it Yourself.如果问题出在 excel 表上,除非你能提供它,否则社区当然无法帮助你——但我确实看到了一些关于编码风格的有用建议,我相信这些建议可以帮助你自己解决。

Curious to learn what You found if You give it a go :)如果你试一试,很想知道你发现了什么:)

From:从:

public List<Contact>Import (string fileName)
{

    var FilePath = $"{Directory.GetCurrentDirectory()}{@""}" + "\\" + fileName;
    FileInfo fileInfo = new FileInfo(FilePath);
    ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
    using (ExcelPackage package = new ExcelPackage(fileInfo))
    {
        ExcelWorksheet worksheet = package.Workbook.Worksheets.FirstOrDefault();
      
        int rowCount = worksheet.Dimension.End.Row;
        for (int row = 2; row <= rowCount; row++)
        {
            Contact con = new Contact();
         
                if (row == 1) con.Libelle = worksheet.Cells[row, row].Value.ToString();
                else if (row == 2) con.Id = (int)worksheet.Cells[row, row].Value;

           
            _context.Add(con);
            _context.SaveChanges(); 
        }
    }
    return _context.Contacts.ToList();
}

TO:至:

public List<Contact> Import(string fileName)
{
    //Try not to use uppercase for local variables, to be able to tell them from member properties
    var FilePath = $"{Directory.GetCurrentDirectory()}{@""}" + "\\" + fileName;

    FileInfo fileInfo = new FileInfo(FilePath);
    ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
    using (ExcelPackage package = new ExcelPackage(fileInfo))
    {
        ExcelWorksheet worksheet = package.Workbook.Worksheets.FirstOrDefault();

        //Here ok, because a workbook has at least one sheet
        int rowCount = worksheet.Dimension.End.Row;
        for (int row = 2; row <= rowCount; row++)
        {
            try
            {
                Contact con = new Contact();

                var cell = worksheet.Cells[row, row];

                if (row == 1)
                {
                    //Do You know how your package handles in case there is nothing in the cell?
                    con.Libelle = cell.Value?.ToString();
                }
                else if (row == 2)
                {
                    if (int.TryParse(cell.Value, out int parsedResult))
                    {
                        con.Id = parsedResult;
                    }
                    else throw new Exception("Invalid data"); //Your direct cast in source code justifies it not being possible to be an exceptional case 'impossible' or you wouldn't write code presuming it ;)
                }
                _context.Add(con);
                _context.SaveChanges();
            }
            catch (Exception ex)
            {
                //Let Your debugger help you pinpoint the problem
                System.Diagnostics.Debug.Write($"problem with row {row} :{ex.ToString()}");
            }
        }
    }
    //Are You sure Contacts are initialized, know the implementation of  the _context
    return _context.Contacts?.ToList() ?? null;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM