最近在项目中使用poi创建excel文件时,需要生成单元格下拉选。
下面是一个demo,注释比较清楚,以此参考。
package poi;
import java.io.FileOutputStream;
import org.apache.poi.hssf.usermodel.DVConstraint;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFDataValidation;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.util.CellRangeAddressList;
public class ExcelSetCheckbox {
public static void main(String[] args) {
String[] list={"广州","深圳","东莞","珠海"};
new ExcelSetCheckbox().createListBox(list);
return ;
}
private void createListBox(String[] list) {
//文件初始化
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet("new sheet");
/**设置单元格格式为文本格式*/ HSSFCellStyle textStyle = workBook.createCellStyle(); HSSFDataFormat format = workBook.createDataFormat(); textStyle.setDataFormat(format.getFormat("@"));
for (int i = 0; i < 10; i++) {
HSSFRow row = sheet.createRow(i);
for (int j = 0; j < 15; j++) {
HSSFCell cell = row.createCell(j);
//普通写入操作
cell.setCellValue("请选择"+i+j);//这是实验
cell.setCellStyle(textStyle);//设置单元格格式为"文本" cell.setCellType(HSSFCell.CELL_TYPE_STRING);
}
}
// 设置数据有效性加载在哪个单元格上,四个参数分别是:起始行、终止行、起始列、终止列
CellRangeAddressList regions = new CellRangeAddressList(0,2,2,4);
//生成下拉框内容
DVConstraint constraint = DVConstraint.createExplicitListConstraint(list);
//绑定下拉框和作用区域
HSSFDataValidation data_validation = new HSSFDataValidation(regions,constraint);
//对sheet页生效
sheet.addValidationData(data_validation);
//针对生效/失效日期单元格有效日期的限定
//生成日期类有效性
DVConstraint constraint3 = DVConstraint.createDateConstraint(DVConstraint.OperatorType.BETWEEN, "1970-1-1",
"2100-1-1", "yyyy-mm-dd");
//创建一个区域
CellRangeAddressList regions3 = new CellRangeAddressList(1,100,3,4);
//有效性--区域 组合
HSSFDataValidation data_validation3 = new HSSFDataValidation(regions3, constraint3);
//对sheet页生效
sheet.addValidationData(data_validation3);
FileOutputStream fileOut;
try {
fileOut = new FileOutputStream("d://workbook.xls");
wb.write(fileOut);
fileOut.close();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("over");
}
}