使用Apache POI创建Excel下拉列表

17

我需要使用Apache POI在Excel文件中创建下拉列表,我已经能够做到了。但是,我不知道如何将下拉列表的第一项设置为默认项。

public class sd {

/**
 * @param args
 * @throws IOException 
 */
public static void main(String[] args) throws IOException {

DataValidation dataValidation = null;
DataValidationConstraint constraint = null;
DataValidationHelper validationHelper = null;

 XSSFWorkbook wb = new XSSFWorkbook();
 XSSFSheet sheet1=(XSSFSheet) wb.createSheet("sheet1");


    validationHelper=new XSSFDataValidationHelper(sheet1);
    CellRangeAddressList addressList = new  CellRangeAddressList(0,5,0,0);
    constraint =validationHelper.createExplicitListConstraint(new String[]{"SELECT","10", "20", "30"});
    dataValidation = validationHelper.createValidation(constraint, addressList);
    dataValidation.setSuppressDropDownArrow(true);      
    sheet1.addValidationData(dataValidation);

    FileOutputStream fileOut = new FileOutputStream("c:\\temp\\vineet.xlsx");
    wb.write(fileOut);
    fileOut.close();
}

}

@Lucifer,我在创建大型列表下拉菜单时遇到了问题。是否有增加列表大小的解决方案? - Aakash Patel
2个回答

7

要设置默认值,只需使用setCellValue(“first_item_value”)。

sheet.getRow(1).getCell(index).setCellValue("my_default_value");

我已经做过了,因为我面临着相同的问题。


1
但是这并不是下拉列表中的一个选项。如果我们需要它在列表中怎么办?比如说,“SELECT”应该作为默认值出现在列表中。 - zeewagon

1

Here is my code:

Cell cell = row.createCell(2);
cell.setCellValue("SELECT");

//2 is the 2nd cell in my case

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接