javaexcel下拉框_Java设置Excel下拉列表
Excel在office2007之前和之后的格式不⼀样,07之前的后缀是.xls,07及07之后.xlsx,针对不同的格式,apache提供了不同的类来操作:HSSF来操作07之前的,XSSF来操作07及07之后。
在l中要对包进⾏依赖,⼀定要两个包都要引⼊,因为这两个包有依赖关系:
org.apache.poi
poi
4.0.1
org.apache.poi
poi-ooxml
4.0.1
对07之前版本的Excel,操作如下:
//textlists存放列表中要展⽰的字符串
String[] textlists = {"doudou1", "doudou2", "doudou3"};
//⽣成⼀个⼯作簿对象
HSSFWorkbook workbook = new HSSFWorkbook();
//⽣成⼀个名称为Info的表单
HSSFSheet sheet = ateSheet("Info");
//设置下拉列表作⽤的单元格(firstrow, lastrow, firstcol, lastcol)
CellRangeAddressList regions = new CellRangeAddressList(1, 100, 0, 0);
//⽣成并设置数据有效性验证
DVConstraint constraint = ateExplicitListConstraint(textlists);
HSSFDataValidation data_validation_list = new HSSFDataValidation(regions, constraint);
//将有效性验证添加到表单
sheet.addValidationData(data_validation_list);
try
{
OutputStream os = new FileOutputStream("D:\\doudou.xls");
workbook.write(os); //将⼯作簿内容输出到Excel⽂件中
os.close();
workbook.close();
} catch (Exception e)
{
e.printStackTrace();
}
对Excel07及之后的⽂件,使⽤的类不同,思想类似:
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = ateSheet("下拉列表测试");
String[] datas = new String[]{"维持", "恢复", "调整"};
XSSFDataValidationHelper dvHelper = new XSSFDataValidationHelper(sheet);
XSSFDataValidationConstraint dvConstraint = (ateExplicitListConstraint(datas); CellRangeAddressList addressList = null;
XSSFDataValidation validation = null;
addressList = new CellRangeAddressList(1,100,0,0);
validation = (ateValidation(dvConstraint, addressList);
//这两⾏设置单元格只能是列表中的内容,否则报错
validation.setSuppressDropDownArrow(true);
validation.setShowErrorBox(true);
sheet.addValidationData(validation);
try
{
OutputStream os = new FileOutputStream("D:\\dou.xlsx");
workbook.write(os);
os.close();
workbook.close();
} catch (Exception e)
{
e.printStackTrace();
}数据验证怎么设置下拉菜单
对以上demo做以记录,便于回顾
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论