/** * 测试单元格样式 * * @author David * @param wb * @param cell * @param td */ private static void setType(HSSFWorkbook wb, HSSFCell cell, Element td) { Attribute typeAttr = td.getAttribute("type"); String type = typeAttr.getValue(); HSSFDataFormat format = wb.createDataFormat(); HSSFCellStyle cellStyle = wb.createCellStyle(); if ("NUMERIC".equalsIgnoreCase(type)) { cell.setCellType(HSSFCell.CELL_TYPE_NUMERIC); Attribute formatAttr = td.getAttribute("format"); String formatValue = formatAttr.getValue(); formatValue = StringUtils.isNotBlank(formatValue) ? formatValue : "#,##0.00"; cellStyle.setDataFormat(format.getFormat(formatValue)); } else if ("STRING".equalsIgnoreCase(type)) { cell.setCellValue(""); cell.setCellType(HSSFCell.CELL_TYPE_STRING); cellStyle.setDataFormat(format.getFormat("@")); } else if ("DATE".equalsIgnoreCase(type)) { cell.setCellType(HSSFCell.CELL_TYPE_NUMERIC); cellStyle.setDataFormat(format.getFormat("yyyy-m-d")); } else if ("ENUM".equalsIgnoreCase(type)) { CellRangeAddressList regions = new CellRangeAddressList( cell.getRowIndex(), cell.getRowIndex(), cell.getColumnIndex(), cell.getColumnIndex()); Attribute enumAttr = td.getAttribute("format"); String enumValue = enumAttr.getValue(); // 加载下拉列表内容 DVConstraint constraint = DVConstraint.createExplicitListConstraint(enumValue.split(",")); // 数据有效性对象 HSSFDataValidation dataValidation = new HSSFDataValidation(regions, constraint); wb.getSheetAt(0).addValidationData(dataValidation); } cell.setCellStyle(cellStyle); }
public static HSSFDataValidation setDataValidationList( short firstRow, short endRow, short col, String[] textList) { // 加载下拉列表内容 DVConstraint constraint = DVConstraint.createExplicitListConstraint(textList); // 设置数据有效性加载在哪个单元格上。 // 四个参数分别是:起始行、终止行、起始列、终止列 CellRangeAddressList regions = new CellRangeAddressList(firstRow, endRow, col, col); // 数据有效性对象 HSSFDataValidation dataValidation = new HSSFDataValidation(regions, constraint); return dataValidation; }