转自:http://www.iteye.com/problems/65041
import org.apache.poi.hssf.usermodel.DVConstraint;
import org.apache.poi.hssf.usermodel.HSSFDataValidation;import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.CellRangeAddressList;
public class PoiTest1{
public static void main(String[] args) {
FileOutputStream out = null;
try {
// excel对象
HSSFWorkbook wb = new HSSFWorkbook();
// sheet对象
HSSFSheet sheet = wb.createSheet("sheet1");
// 输出excel对象out = new FileOutputStream("C://aaa.xls");
// 取得规则 第二行第二列
//例如D6: 5,5,3,3 表示从第六行的第四列,到第六行的第四列 :可以参考二维数组就知道了。
(short) 1, (short) 1, (short) 1);
// 设定规则
sheet.addValidationData(validate);
// 输出excel
wb.write(out);
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public static HSSFDataValidation setValidate(short beginRow,
short beginCol, short endRow, short endCol) {
// // 创建一个规则:1-100的数字
// DVConstraint constraint = DVConstraint.createNumericConstraint(
// DVConstraint.ValidationType.INTEGER,
// DVConstraint.OperatorType.BETWEEN, "1", "100");
DVConstraint constraint = DVConstraint.createExplicitListConstraint(new String[]{"aa","bb","cc"});
// 设定在哪个单元格生效
CellRangeAddressList regions = new CellRangeAddressList(beginRow,
beginCol, endRow, endCol);
// 创建规则对象
HSSFDataValidation ret = new HSSFDataValidation(regions, constraint);
return ret;
}
}