javapoi导出excel设置下拉选择框
基本的过程就是设置⼀个下拉选择框的校验,然后绑定到sheet的指定格⼦上。XSS和HSS的⽅式有些许不同,但是原理是⼀样的。代码⽰例如下:
//性别
数据验证怎么设置下拉菜单String[] datas = new String[]{"男","⼥"};
if(excelType.equals(ExcelTypeEnum.XLSX)){
//数据验证帮助程序
XSSFDataValidationHelper dvHelper2 = new XSSFDataValidationHelper((XSSFSheet) sheet);
XSSFDataValidationConstraint dvConstraint2 = (XSSFDataValidationConstraint) ateExplicitListConstraint(datas);
CellRangeAddressList regions2 =new CellRangeAddressList(1, 5000, 2, 2);
XSSFDataValidation dataValidation2 = (XSSFDataValidation) ateValidation( dvConstrain
t2, regions2);
sheet.addValidationData(dataValidation2);
}else{
//性别
// 设置第5列的2-5000⾏为下拉列表
CellRangeAddressList regions2 = new CellRangeAddressList(1, 5000, 2, 2);
// 创建下拉列表数据
DVConstraint constraint2 = ateExplicitListConstraint(datas);
// 绑定
HSSFDataValidation dataValidation2 = new HSSFDataValidation(regions2, constraint2);
sheet.addValidationData(dataValidation2);
}
------------
完整的⼀个⽰例代码如下。导⼊包后可以直接运⾏实验。
package com.insigma;
import java.io.FileOutputStream;
import org.apache.poi.ss.util.CellRangeAddressList;
import org.apache.poi.xssf.usermodel.XSSFDataValidation;
import org.apache.poi.xssf.usermodel.XSSFDataValidationConstraint;
import org.apache.poi.xssf.usermodel.XSSFDataValidationHelper;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExcelTest {
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 = ateSheet("下拉列表测试");
String[] datas = new String[] {"男","⼥"};
XSSFDataValidationHelper dvHelper = new XSSFDataValidationHelper(sheet);
XSSFDataValidationConstraint dvConstraint = (XSSFDataValidationConstraint) ateExplicitListConstraint(datas);
CellRangeAddressList addressList = new CellRangeAddressList(0, 100, 0, 0);
XSSFDataValidation validation = (XSSFDataValidation) ateValidation( dvConstraint, addressList);
sheet.addValidationData(validation);
FileOutputStream stream = new FileOutputStream(filePath);
workbook.write(stream);
stream.close();
}
}
-----------------
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论