Add List Validation to Column except the first two rows

为君一笑 提交于 2019-12-08 00:57:40

问题


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?


回答1:


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.




回答2:


ExcelCellBase has an appropriate extensionmethod to get an address string from a range:

public static string GetAddress(int FromRow, int FromColumn, int ToRow, int ToColumn)

ExcelPackage has a public const MaxRows (1048576), which you can use for the ToRow parameter.

Putting this together for your case:

var range = ExcelRange.GetAddress(2, 1, ExcelPackage.MaxRows, 1);
var val = worksheet.DataValidations.AddListValidation(range);


来源:https://stackoverflow.com/questions/29764226/add-list-validation-to-column-except-the-first-two-rows

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!