Excel使用DataValidationHelper(POI)下拉

时间:2016-10-05 07:09:14

标签: java excel apache-poi

我正在使用带有100万行的SXSSFWorkbook(流)生成excel文件(.xlsx)。一列必须包含4-5值的下拉列表。我能够产生这个,但我有两个问题 -

  1. excel花费了大量时间来生成。下拉7分钟,没有250,000行11秒。
  2. 生成文件后无法打开文件,因为它要求恢复最终失败的数据。消息显示“在文件D中检测到错误:\ Test.xlsx已删除功能:从/xl/worksheets/sheet2.xml部分进行数据验证”
  3. 以下是代码段

    DataValidationHelper validationHelper = sh.getDataValidationHelper();
    CellRangeAddressList addressList = new CellRangeAddressList(0, sh.getLastRowNum(), cellnum, cellnum);
    DataValidationConstraint constraint = validationHelper.createExplicitListConstraint(new String[] { "High risk", "Medium risk", "Low risk", "No risk" });
    DataValidation  dataValidation = validationHelper.createValidation(constraint, addressList);
    dataValidation.setSuppressDropDownArrow(true);
    sh.addValidationData(dataValidation);
    

    请建议我更好的解决方案。

1 个答案:

答案 0 :(得分:1)

有一个简单的解决方案。在excel中创建一个隐藏的(或受密码保护的)工作表,并在下拉菜单中使用所需的数据。然后在dataValidationConstraint标记中引用该工作表。下载应该不会花费太多时间。 PFB示例代码

  main(){
new_workbook = new XSSFWorkbook();
hiddenRiskSheet= new_workbook.createSheet("RiskHidden");
createRiskHiddenSheet(hiddenPrepaidSheet);
                hiddenRiskSheet.protectSheet("passw0rd");
                hiddenRiskSheet.enableLocking();
DataValidationHelper validationHelper = null;
CellRangeAddressList addressList = new CellRangeAddressList(0, sh.getLastRowNum(), cellnum, cellnum);
DataValidationConstraint constraint = validationHelper..createFormulaListConstraint("RiskHidden!$A$1:$A$4");
DataValidation  dataValidation = validationHelper.createValidation(constraint, addressList);
dataValidation.setSuppressDropDownArrow(true);
validationHelper.addValidationData(dataValidation); 
}   
public void createRiskHiddenSheet(XSSFSheet hiddenRiskSheet)
     {
            String[] risk = { "High risk", "Medium risk", "Low risk", "No risk" };
            for (int i = 0; i < 4; i++) {
                Row row = hiddenRiskSheet.createRow(i);

                    Cell cell = row.createCell(i);
                    String cat = risk[i];
                    cell.setCellValue(cat);
                }
            }
        }