且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Apache POI-如何限制用户清除Excel工作表中的数据验证

更新时间:2023-11-22 08:21:34

您应该考虑锁定工作表以防止更改,并且只允许解锁的单元格是可编辑的.示例:

You should consider locking the sheet against changes and let only the cells unlocked which shall be editable. Example:

import java.io.*;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;

import org.apache.poi.ss.util.CellRangeAddressList;

class LockDataValidation {

 public static void main(String[] args) {
  try {

   Workbook workbook = new XSSFWorkbook();

   Sheet sheet = workbook.createSheet("Sheet1");

   sheet.createRow(0).createCell(1).setCellValue("Only numbers 10 to 100");

   //DataValidation for cell B2:
   DataValidationHelper dvHelper = sheet.getDataValidationHelper();
   DataValidationConstraint dvConstraint = dvHelper.createNumericConstraint(
    DataValidationConstraint.ValidationType.INTEGER,
    DataValidationConstraint.OperatorType.BETWEEN,
    "10", "100");
   CellRangeAddressList addressList = new CellRangeAddressList(1, 1, 1, 1);            
   DataValidation validation = dvHelper.createValidation(dvConstraint, addressList);
   if(validation instanceof XSSFDataValidation) {
    validation.setSuppressDropDownArrow(false);
    validation.setShowErrorBox(true);
   }
   else {
    validation.setSuppressDropDownArrow(true);
   }
   sheet.addValidationData(validation);

   //create cell B2:
   Cell cell = sheet.createRow(1).createCell(1);

   //set cell B2 unlocked:
   CellStyle cellstyle = workbook.createCellStyle();
   cellstyle.setLocked(false);
   cell.setCellStyle(cellstyle);

   //lock the sheet:
   ((XSSFSheet)sheet).enableLocking();

   FileOutputStream fileOut = new FileOutputStream("Datavalidation.xlsx");
   workbook.write(fileOut);
   fileOut.close();

  } catch (FileNotFoundException fnfex) {
  } catch (IOException ioex) {
  }
 }
}

使用此功能,仅B2是可编辑的,并且防止删除数据验证.如果有人将复制的未经验证的单元格粘贴到带有验证的单元格中,则不加锁定就不会删除数据验证.

With this only B2 is editable and the data validation is protected against removing. Without locking the data validation will simply deleted if someone pastes a copied cell without validation into the cell with validation.

但是,即使现在,也可以将错误的值复制/粘贴到B2中,因为数据验证仅在用户直接在单元格中键入数据时才显示消息并防止输入无效.复制或填充数据时,不会出现消息.参见 https ://support.office.com/zh-CN/article/Apply-data-validation-to-cells-c743a24a-bc48-41f1-bd92-95b6aeeb73c9 .

But even now one can copy/paste wrong values into B2 since data validation is designed to show messages and prevent invalid entries only when users type data directly in a cell. When data is copied or filled, the messages do not appear. See https://support.office.com/en-us/article/Apply-data-validation-to-cells-c743a24a-bc48-41f1-bd92-95b6aeeb73c9.

野外有VBA个宏解决方案正在试图弥补这一差距.参见数据通过apache poi在excel中复制粘贴数据时,验证失败.

There are VBA macro solutions in the wild which are trying to close even this gap. See Data validation fails when copy pasting data in excel made through apache poi.