Add List Validation to Column except the first two rows

狂风中的少年 提交于 2019-12-06 12:38:03

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.

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