首页 > 解决方案 > 如何根据Apache POI中另一个单元格中的值禁用单元格中的编辑?

问题描述

我有一个要求,我只需要向用户询问一个标志,如果该标志为真,我需要他在该行的另一个单元格中输入一个数字。如果它是错误的,那么该单元格应该是不可编辑的。我知道如何对单元格设置限制,但我不知道这种有条件的限制。 在此处输入图像描述

标签: javaapache-poi

解决方案


如果在解析工作表A时 column 中的标志已经存在apache poi,则CellStyle.setLocked可以设置为False如果Truecolumn 中有A。因此,如果工作表受到保护,这些单元格将不会被锁定并且是可编辑的。

但是如果Trueor Falsein 列A将在ExcelGUI 中更改,那么这是不可能的,因为在更改 column 中的值时它不会有条件地更改A。为此,必须有可能对单元格锁定进行条件格式化。但是这种可能性是不存在的,至少不使用VBA.

然后只有数据验证是可能的,它在获取值A时检查是否为真,如果不是则发出警报。可以使用 设置数据验证Bapache poi

例子:

import java.io.FileOutputStream;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.ss.util.CellRangeAddressList;

public class CreateExcelDataValidationIfATrueThenB {

 public static void main(String[] args) throws Exception {

  Workbook workbook = new XSSFWorkbook();
  Sheet sheet = workbook.createSheet("Sheet1");

  DataValidationHelper dvHelper = sheet.getDataValidationHelper();
  DataValidationConstraint dvConstraint = dvHelper.createCustomConstraint("AND(A1, B1<>\"\")");

  CellRangeAddressList addressList = new CellRangeAddressList(-1, -1, 1, 1);
  DataValidation validation = dvHelper.createValidation(dvConstraint, addressList);

  validation.createPromptBox("For column B:", "If column A is True, then please put content in column B, else not.");
  validation.setShowPromptBox(true);
  validation.createErrorBox("Bad Value", "Please put content in column B only if column A is True, else not!");
  validation.setShowErrorBox(true);

  sheet.addValidationData(validation);

  sheet.createRow(0).createCell(0).setCellValue(true);
  sheet.createRow(1).createCell(0).setCellValue(false);
  sheet.createRow(2).createCell(0).setCellValue(false);
  sheet.createRow(3).createCell(0).setCellValue(true);

  workbook.write(new FileOutputStream("CreateExcelDataValidationIfATrueThenB.xlsx"));
  workbook.close();

 }

}

如上所述,VBA在更改 column 中的单元格时,可以使用事件对单元格锁定进行条件格式化A。但apache poi不提供创建VBA代码。因此,如果这是要求,则Excel必须使用已经包含这些宏的模板。


推荐阅读