Search code examples
c#epplus

Validating each row and column of an excel spread sheet


I am uploading an excel file sheet with 5 columns and about 10 rows. I want to validate every row/column and make sure there is data. The columns cannot be null or empty. I am using Epplus.

If some rows don't pass validation, I want to keep track of the row/columns and send this message back to the client. I have only one worksheet. I think it might be better to have an errors model

How can I achieve that and where will this code go?

        //check if there is actually a file being uploaded
        if (FileUpload1.HasFile)
        {
            //load the uploaded file into the memorystream
            using (MemoryStream stream = new MemoryStream(FileUpload1.FileBytes))
            using (ExcelPackage excelPackage = new ExcelPackage(stream))
            {
                //loop all worksheets
                foreach (ExcelWorksheet worksheet in excelPackage.Workbook.Worksheets)
                {
                    //loop all rows
                    for (int i = worksheet.Dimension.Start.Row; i <= worksheet.Dimension.End.Row; i++)
                    {
                        //loop all columns in a row
                        for (int j = worksheet.Dimension.Start.Column; j <= worksheet.Dimension.End.Column; j++)
                        {
                            //add the cell data to the List
                            if (worksheet.Cells[i, j].Value != null)
                            {
                                excelData.Add(worksheet.Cells[i, j].Value.ToString());
                            }
                        }
                    }
                }
            }
        }

Solution

  • I suggest using a simple List<string> to keep track of your errors.

    Something like:

    List<string> errors = new List<string>();
    

    Then in your validation:

    if (String.IsNullOrEmpty(worksheet.Cells[i, j].Value))
        errors.Add($"Worksheet {worksheet.Name}, Row {i}, Column {j} does not contain data.");