我有一个带有标题、empName、empId、部门的 Excel。我需要提供下拉菜单供用户输入部门名称。用户应该只能输入下拉列表中存在的值。我尝试了下面的代码,但它没有验证部门列。 CellRangeAddressList 地址列表 = new CellRangeAddressList(2, 2, 2, 2); DVConstraint dvConstraint = DVConstraint.createExplicitListConstraint(new String[] { "ACCOUNTS", "ISE", "SALES"}); DataValidation dataValidation = new HSSFDataValidation(addressList, dvConstraint); dataValidation.setSuppressDropDownArrow(true); sheet.addValidationData(dataValidation); font.setFontHeightInPoints((短) 16);
最佳答案
以下代码创建一个工作簿,其中包含一个包含标题单元格的工作表
| A | B | C |
1 | empName | empId | Department |
在 A1:C1
中,数据验证列表在 HSSF
中的 C2:C65536
或 C2:C1048576
中XSSF
。
该代码适用于二进制 *.xls
文件 (HSSF
) 以及 Office Open XML
*.xlsx
文件 (XSSF
)。
import java.io.FileOutputStream;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.util.CellRangeAddressList;
class CreateExcelDataValidationListsWholeColumn {
public static void main(String[] args) throws Exception {
Workbook workbook = new HSSFWorkbook();
//Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet("Sheet1");
String[] headers = new String[]{"empName", "empId", "Department"};
Row row = sheet.createRow(0);
for (int c = 0 ; c < headers.length; c++) {
row.createCell(c).setCellValue(headers[c]);
}
//data validation in column B, except first row:
DataValidationHelper dvHelper = sheet.getDataValidationHelper();
DataValidationConstraint dvConstraint = dvHelper.createExplicitListConstraint(new String[]{"ACCOUNTS", "ISE", "SALES"}) ;
int lastRow = workbook.getSpreadsheetVersion().getLastRowIndex();
CellRangeAddressList addressList = new CellRangeAddressList(1, lastRow, 2, 2); // C2:C65536 in HSSF or C2:C1048576 in XSSF
DataValidation validation = dvHelper.createValidation(dvConstraint, addressList);
validation.setShowErrorBox(true);
sheet.addValidationData(validation); // data validation for C2:C65536 in HSSF or C2:C1048576 in XSSF
FileOutputStream out = null;
if (workbook instanceof HSSFWorkbook) {
out = new FileOutputStream("CreateExcelDataValidationListsWholeColumn.xls");
} else if (workbook instanceof XSSFWorkbook) {
out = new FileOutputStream("CreateExcelDataValidationListsWholeColumn.xlsx");
}
workbook.write(out);
workbook.close();
out.close();
}
}
关于java - 如何使用 POI api 验证 Excel 中特定标题名称的所有列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57658171/