Java实现Excel2007创建基本样式,为特定单元设置背景颜色样式,对日期格式进行处理,并对单元格进行简单判空处理
private static CellStyle createBasicStyle(SXSSFWorkbook wb) {
CellStyle cs = wb.createCellStyle();
cs.setAlignment(CellStyle.ALIGN_CENTER);
cs.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
cs.setBorderBottom(CellStyle.BORDER_THIN);
cs.setBorderLeft(CellStyle.BORDER_THIN);
cs.setBorderTop(CellStyle.BORDER_THIN);
cs.setBorderRight(CellStyle.BORDER_THIN);
cs.setWrapText(true);
Font font = wb.createFont();
font.setFontHeightInPoints((short) 9);
font.setFontName("宋体");
cs.setFont(font);
return cs;
}
private static CellStyle createYellowCellStyle(SXSSFWorkbook wb, CellStyle baseStyle) {
CellStyle yellowColorcs = wb.createCellStyle();
yellowColorcs.cloneStyleFrom(baseStyle);
yellowColorcs.setFillForegroundColor(IndexedColors.YELLOW.getIndex());
yellowColorcs.setFillPattern(CellStyle.SOLID_FOREGROUND);
return yellowColorcs;
}
private static CellStyle createRedCellStyle(SXSSFWorkbook wb, CellStyle baseStyle) {
CellStyle redColorcs = wb.createCellStyle();
redColorcs.cloneStyleFrom(baseStyle);
redColorcs.setFillForegroundColor(IndexedColors.RED.getIndex());
redColorcs.setFillPattern(CellStyle.SOLID_FOREGROUND);
return redColorcs;
}
private static CellStyle createDateCellStyle(SXSSFWorkbook wb, CellStyle baseStyle) {
CellStyle datecs = wb.createCellStyle();
datecs.cloneStyleFrom(baseStyle);
XSSFDataFormat format = (XSSFDataFormat) wb.createDataFormat();
datecs.setDataFormat(format.getFormat("yyyy/m/d"));
return datecs;
}
public static SXSSFWorkbook fillUpExlBackgroundColor2007(SXSSFWorkbook wb, String[] dataVector, List<Map<String, Object>> dataList) {
Sheet sheet = wb.getSheetAt(0);
int lastLine = sheet.getLastRowNum();
CellStyle cs = createBasicStyle(wb);
CellStyle yellowColorcs = createYellowCellStyle(wb, cs);
CellStyle redColorcs = createRedCellStyle(wb, cs);
CellStyle datecs = createDateCellStyle(wb, cs);
for (int i = 0; i < dataList.size(); i++) {
Row row = sheet.createRow(lastLine + i + 1);
for (int j = 0; j < dataVector.length; j++) {
String val = nullCheck(dataList.get(i).get(dataVector[j]));
Cell cell = row.createCell(j);
if (IsNumeric(val)) {
cell.setCellValue(doubleNullCheck(val));
cell.setCellStyle(cs);
} else if (isDate(val)) {
cell.setCellValue(DateUtil.stringToDate(val));
cell.setCellStyle(datecs);
} else {
cell.setCellValue(val);
cell.setCellStyle(cs);
}
if (j == 3) {
if (val.equals("报废处理")) {
cell.setCellStyle(redColorcs);
} else if (val.equals("退回管理")) {
cell.setCellStyle(yellowColorcs);
}
}
}
}
return wb;
}