相关包:
import org.apache.poi.hssf.usermodel.DVConstraint;
import org.apache.poi.hssf.usermodel.HSSFDataValidation;
import org.apache.poi.hssf.util.CellRangeAddressList;
数据有效性代码:
/**
* 方法名称:SetDataValidation
* 内容摘要:设置数据有效性
* @param firstRow
* @param firstCol
* @param endRow
* @param endCol
*/
private static HSSFDataValidation SetDataValidation(short firstRow,
short firstCol, short endRow, short endCol) {
//设置下拉列表的内容
String[] textList = {
“列表1”,
“列表2”,
“列表3”,
“列表4”,
“列表5”};
//加载下拉列表内容
DVConstraint constraint = DVConstraint.createExplicitListConstraint(textList);
//设置数据有效性加载在哪个单元格上。
//四个参数分别是:起始行、终止行、起始列、终止列
CellRangeAddressList regions =
new CellRangeAddressList(firstRow,endRow, firstCol, endCol);
//数据有效性对象
HSSFDataValidation data_validation = new HSSFDataValidation(regions, constraint);
return data_validation;
}
添加到Sheet:
//调用接口方法加载数据有效性
HSSFDataValidation data_validation =
SetDataValidation((short)3, (short)(cellIndex+1), (short)500,(short)(cellIndex+1));
aSheet.addValidationData(data_validation);