java - 如果使用 JAVA 和 Apache Poi 粘贴添加内容,则数据验证不起作用

标签 java excel validation apache-poi

我正在使用 Java 代码创建 Excel 工作表。我能够生成工作表,但现在我还必须为特定列添加数据验证。这是我的代码:

HSSFWorkbook wb = new HSSFWorkbook();
    HSSFSheet sheet = wb.createSheet("Data Validation");

    // set style to the cell
    CellStyle style = wb.createCellStyle();        
    style.setFillForegroundColor(IndexedColors.YELLOW.getIndex());
    style.setFillPattern(CellStyle.SOLID_FOREGROUND);
    style.setBorderRight(CellStyle.BORDER_MEDIUM);
    style.setBorderBottom(CellStyle.BORDER_THIN);
    Row row = sheet.createRow((short) 0);

    // Create a cell and put a value in it.
    Cell cell = row.createCell(0);
    cell.setCellValue("First Name");
    cell.setCellStyle(style);
    cell = row.createCell(1);
    cell.setCellValue("Last Name");
    cell.setCellStyle(style);
    cell = row.createCell(2);
    cell.setCellValue("Age");
    cell.setCellStyle(style);


    //CellRangeAddressList(index_of_starting_row, index_of_ending_row, index_of_starting_column,index_of_ending_column);
    CellRangeAddressList addressList = new CellRangeAddressList(1, 90, 2, 2);
    DVConstraint dvConstraint = DVConstraint.createExplicitListConstraint(new String[]{"10", "20", "30"});
    DataValidation dataValidation = new HSSFDataValidation(addressList, dvConstraint);
    dataValidation.setSuppressDropDownArrow(true);
    sheet.addValidationData(dataValidation);

    // show error
    dataValidation.setErrorStyle(DataValidation.ErrorStyle.STOP);
    dataValidation.createErrorBox("Box Title", "Message Text");
    String file = "test.xls";
    FileOutputStream fileOut = new FileOutputStream(file);
    wb.write(fileOut);
    fileOut.close();

当我输入 10、20、30 以外的数字时,数据验证正在工作。但是,如果我在列中粘贴一些其他数字,那么验证就会被超越。有什么办法可以解决这个问题吗?

我正在使用 Apache poi 库。

最佳答案

Data Validation可以被任何为单元格赋值的编程所取代。这不限于 [tag:apache:poi]。即使 VBE 的立即窗口也可以绕过数据验证限制,例如:

activecell = 99

... 其中ActiveCell保存简单的数据验证,如下所示。

         data_validation_bypass

关于java - 如果使用 JAVA 和 Apache Poi 粘贴添加内容,则数据验证不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34669419/

相关文章:

c# - 大数据损坏的 excel 文件

html - 是否有类似黑莓的条件注释来验证网络应用程序中的特定元标记?

java - hibernate 或 oracle 支持时间线?

Java 方法在 ArrayList 中查找匹配项

vba - 运行vb代码计算相似度时定义首字母缩略词

python - 有没有办法根据与 Pandas 中另一列关联的值来填充列?

javascript - 如何验证用户编写的PGP公钥?

javascript - h5Validate 函数调用应在表单验证时完成

java - 为什么@NotBlank 不显示为导入

java - 如何使 String 类可迭代?可能的?