我正在使用 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保存简单的数据验证,如下所示。
关于java - 如果使用 JAVA 和 Apache Poi 粘贴添加内容,则数据验证不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34669419/