版本poi3.8
public class Test {
public static void main(String[] args) {
FileInputStream in = null;
String outputPath = null;
try {
//创建Workbook
in = new FileInputStream("c:/temp.xlsx");
Workbook workbook = WorkbookFactory.create(in);
Sheet sheet =workbook.getSheetAt(1);
Row row = sheet.getRow(3);
Cell cell = row.getCell(7);
String[] textList = { "空闲1", "已用2" };
sheet.addValidationData(setDataValidation(sheet,textList, 3,3, 7, 7));
cell.setCellValue("空闲1");
FileOutputStream out = new FileOutputStream("c:/aaa.xlsx");
workbook.write(out);
out.close();
} catch (Exception e) {
e.printStackTrace();
} finally{
try {
if(in != null){
in.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static DataValidation setDataValidation(Sheet sheet,String[] textList, int firstRow, int endRow, int firstCol, int endCol) {
DataValidationHelper helper = sheet.getDataValidationHelper();
// 加载下拉列表内容
DataValidationConstraint constraint = helper.createExplicitListConstraint(textList);
// DVConstraint constraint = new DVConstraint();
constraint.setExplicitListValues(textList);
// 设置数据有效性加载在哪个单元格上。
// 四个参数分别是:起始行、终止行、起始列、终止列
CellRangeAddressList regions = new CellRangeAddressList((short) firstRow, (short) endRow, (short) firstCol, (short) endCol);
// 数据有效性对象
DataValidation data_validation = helper.createValidation(constraint, regions);
//DataValidation data_validation = new DataValidation(regions, constraint);
return data_validation;
}