我正在使用Poi版本3.16。我正在用Groovy编写代码。 我尝试在同一列中添加2个不同的数据验证。第一个被接受,但是第二个失败。有人有做正确的主意吗?到目前为止非常感谢。
// Something like that
FileOutputStream fileOut = new FileOutputStream("pois-test.xls");
def workbook = new XSSFWorkbook();
def sheet = workbook.createSheet("Sheet1");
// Create 2 Dropdownlists
addMyValidation(1, 10, 3, 3, new String[]{"One", "Two", "Three"});
addMyValidation(15, 25, 3, 3, new String[]{"A", "B", "C"}); // second one failed without errormessage
Boolean addMyValidation(int firstRow, int lastRow, int firstCol, int lastCol, String[] listOfValue)
{
def helper = new XSSFDataValidationHelper(sheet);
def constraint = helper.createExplicitListConstraint(listOfValue);
CellRangeAddressList range = new CellRangeAddressList(firstRow, lastRow, firstCol, lastCol);
def validation = helper.createValidation(constraint, range);
validation.setErrorStyle(ErrorStyle.STOP);
validation.setSuppressDropDownArrow(true);
validation.setEmptyCellAllowed(false);
validation.setShowPromptBox(true);
validation.setShowErrorBox(true);
sheet.addValidationData(validation);
return (true);
}
答案 0 :(得分:1)
使用Java
和apache poi
为我工作。不过,也应该使用您的Groovy
代码。
由于行ID和列ID都是基于0的,您可能不完全确定第15行实际上在哪里吗?
以下完整代码有效:
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 CreateExcelDataValidation {
static Sheet sheet = null;
static boolean addMyValidation(int firstRow, int lastRow, int firstCol, int lastCol, String[] listOfValue) {
DataValidationHelper helper = sheet.getDataValidationHelper();
DataValidationConstraint constraint = helper.createExplicitListConstraint(listOfValue);
CellRangeAddressList range = new CellRangeAddressList(firstRow, lastRow, firstCol, lastCol);
DataValidation validation = helper.createValidation(constraint, range);
validation.setErrorStyle(DataValidation.ErrorStyle.STOP);
validation.setSuppressDropDownArrow(true);
validation.setEmptyCellAllowed(false);
validation.setShowPromptBox(true);
validation.setShowErrorBox(true);
sheet.addValidationData(validation);
return true;
}
public static void main(String[] args) throws Exception {
Workbook workbook = new XSSFWorkbook();
sheet = workbook.createSheet("Data Validation");
sheet.createRow(0).createCell(3).setCellValue("Col 3");
sheet.createRow(1).createCell(0).setCellValue("Row 1");
sheet.createRow(10).createCell(0).setCellValue("Row 10");
sheet.createRow(15).createCell(0).setCellValue("Row 15");
sheet.createRow(25).createCell(0).setCellValue("Row 25");
addMyValidation(1, 10, 3, 3, new String[]{"One", "Two", "Three"});
addMyValidation(15, 25, 3, 3, new String[]{"A", "B", "C"});
FileOutputStream out = new FileOutputStream("CreateExcelDataValidation.xlsx");
workbook.write(out);
workbook.close();
out.close();
}
}