<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.8</version>
</dependency>
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
public class ExcelUtil {
public static class Value {
private String value;
private Short color;
public Value(String value) {
this.value = value;
}
public Value(String value, Short color) {
this.value = value;
this.color = color;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public Short getColor() {
return color;
}
public void setColor(Short color) {
this.color = color;
}
}
public static HSSFWorkbook getHSSFWorkbook(String sheetName, String[] title, Value[][] values, HSSFWorkbook wb) {
HSSFSheet sheet = wb.createSheet(sheetName);
for (int i = 0; i < title.length; i++) {
sheet.setColumnWidth(i, 20 * 256);
}
HSSFRow row = sheet.createRow(0);
HSSFFont headFont = wb.createFont();
headFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);//粗体显示
headFont.setColor(HSSFColor.WHITE.index);
HSSFCellStyle headCellStyle = wb.createCellStyle();
headCellStyle.setFont(headFont);//选择需要用到的字体格式
headCellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式
headCellStyle.setFillForegroundColor(HSSFColor.BLACK.index);
headCellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
for (int i = 0; i < title.length; i++) {
HSSFCell cell = row.createCell(i);
cell.setCellValue(title[i]);
cell.setCellStyle(headCellStyle);
}
HSSFFont redFont = wb.createFont();
redFont.setColor(HSSFColor.RED.index);
for (int i = 0; i < values.length; i++) {
row = sheet.createRow(i + 1);
for (int j = 0; j < values[i].length; j++) {
HSSFCell cur = row.createCell(j);
if (values[i][j] == null || StringUtils.isBlank(values[i][j].getValue())) {
continue;
}
cur.setCellValue(values[i][j].getValue());
if (ObjectUtils.equals(values[i][j].getColor(), HSSFColor.RED.index)) {
HSSFCellStyle cellStyle = wb.createCellStyle();
cur.setCellStyle(cellStyle);
cellStyle.setFont(redFont);
}
}
}
return wb;
}
}