有一种情况,初始化一个列时能用这种方法,但在循环调用时却不能制造多个下拉,原因是输入输出流的问题,每做完一列的下拉就要关闭流关闭文件,然后再打开就可以制造多个列了,不能一次制造多个列的下拉。
HSSF:
- public class POI
- {
- public static void main(String [] args)
- {
- String [] list={"东软","华信","SAP","海辉"};
- new POI().createListBox(list);
- return;
- }
- public void createListBox (String [] list)
- {
- //文件初始化
- HSSFWorkbook wb = new HSSFWorkbook();
- HSSFSheet sheet = wb.createSheet("new sheet");
- //在第一行第一个单元格,插入下拉框
- HSSFRow row = sheet.createRow(0);
- HSSFCell cell = row.createCell(0);
- //普通写入操作
- cell.setCellValue("请选择");//这是实验
- //生成下拉列表
- //只对(0,0)单元格有效
- CellRangeAddressList regions = new CellRangeAddressList(0,0,0,0);
- //生成下拉框内容
- DVConstraint constraint = DVConstraint.createExplicitListConstraint(list);
- //绑定下拉框和作用区域
- HSSFDataValidation data_validation = new HSSFDataValidation(regions,constraint);
- //对sheet页生效
- sheet.addValidationData(data_validation);
- //写入文件
- FileOutputStream fileOut;
- try {
- fileOut = new FileOutputStream("workbook.xls");
- wb.write(fileOut);
- fileOut.close();
- } catch (Exception e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- //结束
- System.out.println("Over");
- }
- }
XSSF:
public class Xiala {
public static void main(String[] args) {
try
{
dropDownList42007("D:\\test.xlsx");
}
catch (Exception e) {
e.printStackTrace();
}
}
public static void dropDownList42007(String filePath)
throws Exception {
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet("下拉列表测试");
String[] datas = new String[] {"维持","恢复","调整"};
XSSFDataValidationHelper dvHelper = new XSSFDataValidationHelper(sheet);
XSSFDataValidationConstraint dvConstraint = (XSSFDataValidationConstraint) dvHelper
.createExplicitListConstraint(datas);
CellRangeAddressList addressList = null;
XSSFDataValidation validation = null;
addressList = new CellRangeAddressList(1, 100, 0, 0);
validation = (XSSFDataValidation) dvHelper.createValidation(
dvConstraint, addressList);
// 07默认setSuppressDropDownArrow(true);
// validation.setSuppressDropDownArrow(true);
// validation.setShowErrorBox(true);
sheet.addValidationData(validation);
FileOutputStream stream = new FileOutputStream(filePath);
workbook.write(stream);
stream.close();
addressList = null;
validation = null;
}
}