java - 如何根据Apache POI中另一个单元格中的值禁用单元格中的编辑?
问题描述
我有一个要求,我只需要向用户询问一个标志,如果该标志为真,我需要他在该行的另一个单元格中输入一个数字。如果它是错误的,那么该单元格应该是不可编辑的。我知道如何对单元格设置限制,但我不知道这种有条件的限制。
解决方案
如果在解析工作表A
时 column 中的标志已经存在apache poi
,则CellStyle.setLocked可以设置为False
如果True
column 中有A
。因此,如果工作表受到保护,这些单元格将不会被锁定并且是可编辑的。
但是如果True
or False
in 列A
将在Excel
GUI 中更改,那么这是不可能的,因为在更改 column 中的值时它不会有条件地更改A
。为此,必须有可能对单元格锁定进行条件格式化。但是这种可能性是不存在的,至少不使用VBA
.
然后只有数据验证是可能的,它在获取值A
时检查是否为真,如果不是则发出警报。可以使用 设置数据验证。B
apache 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
必须使用已经包含这些宏的模板。