Search code examples
excelvalidationc#-4.0epplusepplus-4

Add List Validation to Column except the first two rows


I am trying to add a dropdown (list validation) upon creating the excel, I already found the way to add it to whole column but my scenario is different because I only add the validation to whole column except the first row and second row.

This is what I have tried so far:

 public MemoryStream GetExcelSheet()
    {
        using (var package = new ExcelPackage())
        {
            ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("Test");

            var val = worksheet.DataValidations.AddListValidation("A:A");

            val.Formula.Values.Add("Male");
            val.Formula.Values.Add("Female");
            val.ShowErrorMessage = true;

            worksheet.Cells["A1"].Formula = null;


            var stream = new MemoryStream(package.GetAsByteArray());
            return stream;
        }
    }

I am trying to nullify it:

worksheet.Cells["A1"].Formula = null;

hoping that it will remove the validation on a certain cell but it's not working.

I also tried

var val = worksheet.DataValidations.AddListValidation("A2:A");

specifying the starting row number but the generated Excel file is corrupted.

Any help on this please?


Solution

  • AFAIK there is no way to set a range in excel of "Row 2 to Infinity" unfortunately. So something like "A2:A" will not work.

    To demo, try creating a worksheet in Excel manually with a validation list and save it (nothing to do with code). Set the val list on all of column A and then click A1 and remove the list from it only. If you then rename the xlsx to .zip, open it, and look at the sheet1.xml file you will see this:

    <dataValidation type="list" allowBlank="1" showInputMessage="1" showErrorMessage="1" sqref="A2:A1048576">
        <formula1>"Male,Female"</formula1>
    </dataValidation>
    

    Note the sqref. Basically, excel sets the range from A2 to the max number of rows in the excel 2007 format of 1,048,576. So no reason you couldn't do the same.