POI导出Excel设置背景色踩坑,解决背景色全黑的问题及指定列添加背景色,自定义颜色
一.自定义颜色
话不多说,上代码,这里改的是字体颜色,一些信息放在注释中了
String str = "#666666";//灰色--->16进制颜色信息,网上百度就行,有特定的网站例如:https://www.tpyyes.com/tool/rgb.html
//处理把它转换成十六进制并放入一个数
int[] color=new int[3];
color[0]=Integer.parseInt(str.substring(1, 3), 16);
color[1]=Integer.parseInt(str.substring(3, 5), 16);
color[2]=Integer.parseInt(str.substring(5, 7), 16);
//自定义颜色
HSSFPalette palette = workbook.getCustomPalette();
palette.setColorAtIndex(HSSFColor.GOLD.index,(byte)color[0], (byte)color[1], (byte)color[2]);//此处颜色名可随意使用,但是下面引用的时候要保持一致
// 设置字体
HSSFFont font = workbook.createFont();
//设置字体颜色为红色
font.setColor(HSSFColor.GOLD.index);//颜色名字与上面自定义的保持一致
二.背景色全黑(无效)的问题解决
poi设置背景色的时候,一定要设置填充样式(setFillPattern方法),要达到上图所示效果,填充样式一定要设置为SOLID_FOREGROUND
//设置样式;
HSSFCellStyle style = workbook.createCellStyle();
style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);//设置前景填充样式
style.setFillForegroundColor(IndexedColors. GREY_25_PERCENT.index);//前景填充色
注意:如果改任何背景色,均为黑色时,及设置背景色无效,原因时因为poi代码问题
如果填充颜色时使用setFillBackgroundColor方法,则颜色设置无效,可尝试改为setFillForegroundColor方法
本人遇到的异常方式:
style.setFillBackgroundColor(IndexedColors. GREY_25_PERCENT.index);// 设置背景颜色
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
三.指定列添加背景色
在指定列添加背景颜色,要在将查询出的数据设置到sheet对应的单元格中的循环里面进行的,以上图的指标名称列为例,下面添加代码片段,稍后贴出完整代码
HSSFCellStyle style = this.getStyle(workbook); //单元格样式对象(普通)
HSSFCellStyle styleColor = this.getStyleColor(workbook); //单元格样式对象有色
//将查询出的数据设置到sheet对应的单元格中
for (int i = 0; i < dataList.size(); i++) {
HashMap<String, Object> obj = dataList.get(i);//遍历每个对象
HSSFRow row = sheet.createRow(i + 2);//创建所需的行数
int cellIndex = 0;
for (Map.Entry<String, String> entry : keyNameMap.entrySet()) {
HSSFCell cell = null;
cell = row.createCell(cellIndex, HSSFCell.CELL_TYPE_STRING);
cell.setCellValue(obj.get(entry.getKey()).toString());
cell.setCellStyle(style);
//此处是指定列添加背景色
HSSFCell cell1 = row.createCell(0,HSSFCell.CELL_TYPE_STRING);//指定列是第几列
cell1.setCellStyle(styleColor);//指定列的样式设置
cell1.setCellValue(obj.get("指标名称").toString());//指定列的内容赋值,传的是列名
++cellIndex;
}
}
四.完整的代码
注:背景色代码在getStyleColor方法中,注释中的不对
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.*;
import org.apache.shiro.util.CollectionUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @version 1.0
* @name
* @description
* @date 20210616
*/
public class ExportExcelUtil {
/**
* 显示的导出表的标题
*/
private String title;
/**
* 需要导出的数据集合
*/
private List<HashMap<String, Object>> dataList = new ArrayList<HashMap<String, Object>>();
private LinkedHashMap<String, String> keyNameMap = new LinkedHashMap<>();
/**
* 输入流对象
*/
private HttpServletRequest request;
/**
* 输出流对象
*/
private HttpServletResponse response;
/**
* 合并单元格
*/
private LinkedList<int[]> mergeRowsList;
/**
* @description 构造方法,传入要导出的数据
*/
public BatchMaintenanceRiskIndicatorsExportExcelUtil(String title, List<HashMap<String, Object>> dataList, HttpServletRequest request, HttpServletResponse response, LinkedHashMap<String, String> keyNameMap) {
this.title = title;
this.dataList = dataList;
this.request = request;
this.response = response;
this.keyNameMap = keyNameMap;
}
public void export(String fileName) throws Exception {
try {
HSSFWorkbook workbook = new HSSFWorkbook(); // 创建工作簿对象
HSSFSheet sheet = workbook.createSheet(); // 创建工作表
// 产生表格标题行
HSSFRow rowm = sheet.createRow(0);
HSSFCell cellTiltle = rowm.createCell(0);
//设置标题和单元格样式
HSSFCellStyle columnTopStyle = this.getColumnTopStyle(workbook); //获取列头样式对象
HSSFCellStyle style = this.getStyle(workbook); //单元格样式对象
HSSFCellStyle styleColor = this.getStyleColor(workbook); //单元格样式对象有色
//合并单元格
sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, (keyNameMap.size() - 1)));
if (!CollectionUtils.isEmpty(mergeRowsList)) {
for (int[] a : mergeRowsList) {
sheet.addMergedRegion(new CellRangeAddress(a[0], a[1], a[2], a[3]));
}
}
cellTiltle.setCellStyle(columnTopStyle);
cellTiltle.setCellValue(title);
// 定义所需列数
int columnNum = keyNameMap.size();
HSSFRow rowRowName = sheet.createRow(1); // 在索引1的位置创建行(最顶端的行开始的第2行)
HSSFCellStyle rowTopStyle = this.getRowTopStyle(workbook); //获取列头样式对象
// 将列头设置到sheet的单元格中
int sizeIndex = 0;
for (Map.Entry<String, String> entry : keyNameMap.entrySet()) {
HSSFCell cellRowName = rowRowName.createCell(sizeIndex); //创建列头对应个数的单元格
cellRowName.setCellType(HSSFCell.CELL_TYPE_STRING); //设置列头单元格的数据类型
HSSFRichTextString text = new HSSFRichTextString(entry.getValue());
cellRowName.setCellValue(text); //设置列头单元格的值
cellRowName.setCellStyle(rowTopStyle);
++sizeIndex;
}
//将查询出的数据设置到sheet对应的单元格中
for (int i = 0; i < dataList.size(); i++) {
HashMap<String, Object> obj = dataList.get(i);//遍历每个对象
HSSFRow row = sheet.createRow(i + 2);//创建所需的行数
int cellIndex = 0;
for (Map.Entry<String, String> entry : keyNameMap.entrySet()) {
HSSFCell cell = null;
cell = row.createCell(cellIndex, HSSFCell.CELL_TYPE_STRING);
cell.setCellValue(obj.get(entry.getKey()).toString());
cell.setCellStyle(style);
HSSFCell cell1 = row.createCell(0,HSSFCell.CELL_TYPE_STRING);
cell1.setCellStyle(styleColor);
cell1.setCellValue(obj.get("指标名称").toString());
++cellIndex;
}
}
sheet.autoSizeColumn(0);
//让列宽随着导出的列长自动适应
for (int colNum = 0; colNum < columnNum; colNum++) {
int columnWidth = sheet.getColumnWidth(colNum) / 256;
for (int rowNum = 0; rowNum < sheet.getLastRowNum(); rowNum++) {
HSSFRow currentRow;
//当前行未被使用过
if (sheet.getRow(rowNum) == null) {
currentRow = sheet.createRow(rowNum);
} else {
currentRow = sheet.getRow(rowNum);
}
if (currentRow.getCell(colNum) != null) {
//取得当前的单元格
HSSFCell currentCell = currentRow.getCell(colNum);
//如果当前单元格类型为字符串
if (currentCell.getCellType() == HSSFCell.CELL_TYPE_STRING) {
int length = currentCell.getStringCellValue().getBytes().length;
if (columnWidth < length) {
//将单元格里面值大小作为列宽度
columnWidth = length;
}
}
}
}
//再根据不同列单独做下处理
if (colNum == 11|| colNum==12) {
sheet.setColumnWidth(colNum,(columnWidth + 6)*256);
} else{
sheet.setColumnWidth(colNum,(columnWidth + 4 )*256);
}
}
if (workbook != null) {
try {
response.setCharacterEncoding("UTF-8");
response.setContentType("multipart/form-data");
String userAgent = request.getHeader("User-Agent");
byte[] bytes = userAgent.contains("MSIE") ? fileName.getBytes() : fileName.getBytes("UTF-8"); // fileName.getBytes("UTF-8")处理safari的乱码问题
String fileNameEncode = new String(bytes, "ISO-8859-1"); // 各浏览器基本都支持ISO编码
response.setHeader("Content-disposition",
String.format("attachment; filename=\"%s\"", fileNameEncode + ".xls"));
OutputStream out1 = response.getOutputStream();
workbook.write(out1);
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* @description 标题行的单元格样式
*/
public HSSFCellStyle getColumnTopStyle(HSSFWorkbook workbook) {
// 设置字体
HSSFFont font = workbook.createFont();
//设置字体大小
font.setFontHeightInPoints((short) 10);
//字体加粗
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
//设置字体名字
font.setFontName("Courier New");
//设置字体颜色为红色
font.setColor(HSSFColor.RED.index);
//设置样式;
HSSFCellStyle style = workbook.createCellStyle();
style.setFillForegroundColor(IndexedColors.BLUE.getIndex());
//设置底边框;
style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
//设置底边框颜色;
style.setBottomBorderColor(HSSFColor.BLACK.index);
//设置左边框;
style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
//设置左边框颜色;
style.setLeftBorderColor(HSSFColor.BLACK.index);
//设置右边框;
style.setBorderRight(HSSFCellStyle.BORDER_THIN);
//设置右边框颜色;
style.setRightBorderColor(HSSFColor.BLACK.index);
//设置顶边框;
style.setBorderTop(HSSFCellStyle.BORDER_THIN);
//设置顶边框颜色;
style.setTopBorderColor(HSSFColor.BLACK.index);
// style.setFillPattern(HSSFCellStyle.FINE_DOTS );
// style.setFillBackgroundColor(HSSFColor.GREEN.index);// 设置背景颜色
//在样式用应用设置的字体;
style.setFont(font);
//设置自动换行;
style.setWrapText(false);
//设置水平对齐的样式为左对齐;
style.setAlignment(HSSFCellStyle.ALIGN_LEFT);
//设置垂直对齐的样式为居中对齐;
style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
return style;
}
/**
* @description 标题列的单元格样式
*/
public HSSFCellStyle getRowTopStyle(HSSFWorkbook workbook) {
// 设置字体
HSSFFont font = workbook.createFont();
//设置字体大小
font.setFontHeightInPoints((short) 11);
//字体加粗
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
//设置字体名字
font.setFontName("Courier New");
//设置样式;
HSSFCellStyle style = workbook.createCellStyle();
style.setFillForegroundColor(IndexedColors.BLUE.getIndex());
//设置底边框;
style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
//设置底边框颜色;
style.setBottomBorderColor(HSSFColor.BLACK.index);
//设置左边框;
style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
//设置左边框颜色;
style.setLeftBorderColor(HSSFColor.BLACK.index);
//设置右边框;
style.setBorderRight(HSSFCellStyle.BORDER_THIN);
//设置右边框颜色;
style.setRightBorderColor(HSSFColor.BLACK.index);
//设置顶边框;
style.setBorderTop(HSSFCellStyle.BORDER_THIN);
//设置顶边框颜色;
style.setTopBorderColor(HSSFColor.BLACK.index);
//在样式用应用设置的字体;
style.setFont(font);
//设置自动换行;
style.setWrapText(false);
//设置水平对齐的样式为居中对齐;
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
//设置垂直对齐的样式为居中对齐;
style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
return style;
}
/**
* @description 列数据信息单元格样式
*/
public HSSFCellStyle getStyle(HSSFWorkbook workbook) {
// 设置字体
HSSFFont font = workbook.createFont();
//设置字体大小
//font.setFontHeightInPoints((short)10);
//字体加粗
//font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
//设置字体名字
font.setFontName("Courier New");
//设置样式;
HSSFCellStyle style = workbook.createCellStyle();
//设置底边框;
style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
//设置底边框颜色;
style.setBottomBorderColor(HSSFColor.BLACK.index);
//设置左边框;
style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
//设置左边框颜色;
style.setLeftBorderColor(HSSFColor.BLACK.index);
//设置右边框;
style.setBorderRight(HSSFCellStyle.BORDER_THIN);
//设置右边框颜色;
style.setRightBorderColor(HSSFColor.BLACK.index);
//设置顶边框;
style.setBorderTop(HSSFCellStyle.BORDER_THIN);
//设置顶边框颜色;
style.setTopBorderColor(HSSFColor.BLACK.index);
//在样式用应用设置的字体;
style.setFont(font);
//设置自动换行;
style.setWrapText(false);
//设置水平对齐的样式为左对齐;
style.setAlignment(HSSFCellStyle.ALIGN_LEFT);
//设置垂直对齐的样式为居中对齐;
style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
return style;
}
public static CellStyle getStyle(Workbook workbook) {
CellStyle style = workbook.createCellStyle();
style.setFillForegroundColor(IndexedColors.BLUE.getIndex());
//设置底边框;
style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
//设置底边框颜色;
style.setBottomBorderColor(HSSFColor.BLACK.index);
//设置左边框;
style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
//设置左边框颜色;
style.setLeftBorderColor(HSSFColor.BLACK.index);
//设置右边框;
style.setBorderRight(HSSFCellStyle.BORDER_THIN);
//设置右边框颜色;
style.setRightBorderColor(HSSFColor.BLACK.index);
//设置顶边框;
style.setBorderTop(HSSFCellStyle.BORDER_THIN);
//设置顶边框颜色;
style.setTopBorderColor(HSSFColor.BLACK.index);
//在样式用应用设置的字体;
// style.setFont(font);
//设置自动换行;
style.setWrapText(false);
//设置水平对齐的样式为居中对齐;
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
//设置垂直对齐的样式为居中对齐;
style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
return style;
}
//日期格式化
public static String formatDate(Date date) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
String newDate = sdf.format(date);
return newDate;
}
//未处理公式
public static String getCellValue(XSSFCell cell) {
if (cell == null) {
return null;
}
switch (cell.getCellType()) {
case XSSFCell.CELL_TYPE_STRING:
return cell.getRichStringCellValue().getString().trim();
case XSSFCell.CELL_TYPE_NUMERIC:
if (DateUtil.isCellDateFormatted(cell)) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
return sdf.format(cell.getDateCellValue());
} else {
return String.valueOf(cell.getNumericCellValue());
}
case XSSFCell.CELL_TYPE_BOOLEAN:
return String.valueOf(cell.getBooleanCellValue());
case XSSFCell.CELL_TYPE_FORMULA:
return cell.getCellFormula();
default:
return null;
}
}
public static void copySheet(XSSFWorkbook workbook, XSSFSheet sheet, XSSFSheet sheetCreat) {
MergerRegion(sheetCreat, sheet);
int firstRow = sheet.getFirstRowNum();
int lastRow = sheet.getLastRowNum();
for (int a = firstRow; a <= lastRow; a++) {
// 创建新建excel Sheet的行
XSSFRow rowCreat = sheetCreat.createRow(a);
// 取得源有excel Sheet的行
XSSFRow row = sheet.getRow(a);
rowCreat.setRowStyle(row.getRowStyle());
// 单元格式样
int firstCell = row.getFirstCellNum();
int lastCell = row.getLastCellNum();
for (int j = firstCell; j < lastCell; j++) {
// 自动适应列宽
sheetCreat.autoSizeColumn(j);
XSSFCell newCell = rowCreat.createCell(j);
String strVal = "";
if (row.getCell(j) == null) {
} else {
strVal = row.getCell(j).getStringCellValue();
}
newCell.getRow().setHeight(row.getCell(j).getRow().getHeight());
XSSFCellStyle toStyle = workbook.createCellStyle();
copyCellStyle(row.getCell(j).getCellStyle(), toStyle);
newCell.setCellStyle(toStyle);
newCell.setCellValue(strVal);
}
}
}
public static void copyCellStyle(XSSFCellStyle fromStyle, XSSFCellStyle toStyle) {
toStyle.cloneStyleFrom(fromStyle);
toStyle.setFillForegroundColor(fromStyle.getFillForegroundColor());
toStyle.setFillPattern(fromStyle.getFillPattern());
toStyle.setFillBackgroundColor(fromStyle.getFillBackgroundColor());
}
/**
* * 复制原有sheet的合并单元格到新创建的sheet
* *
* * @param sheetCreat
* * 新创建sheet
* * @param sheet
* * 原有的sheet
*/
private static void MergerRegion(XSSFSheet sheetCreat, XSSFSheet sheet) {
int sheetMergerCount = sheet.getNumMergedRegions();
for (int i = 0; i < sheetMergerCount; i++) {
CellRangeAddress mergedRegion = sheet.getMergedRegion(i);
sheetCreat.addMergedRegion(mergedRegion);
}
}
/**
* @description 列数据信息单元格样式2
*/
public HSSFCellStyle getStyleColor(HSSFWorkbook workbook) {
String str = "#666666";
//处理把它转换成十六进制并放入一个数
int[] color=new int[3];
color[0]=Integer.parseInt(str.substring(1, 3), 16);
color[1]=Integer.parseInt(str.substring(3, 5), 16);
color[2]=Integer.parseInt(str.substring(5, 7), 16);
//自定义颜色
HSSFPalette palette = workbook.getCustomPalette();
palette.setColorAtIndex(HSSFColor.GOLD.index,(byte)color[0], (byte)color[1], (byte)color[2]);
// 设置字体
HSSFFont font = workbook.createFont();
//设置字体大小
//font.setFontHeightInPoints((short)10);
//字体加粗
//font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
//设置字体名字
font.setFontName("Courier New");
//设置字体颜色为红色
font.setColor(HSSFColor.GOLD.index);
//设置样式;
HSSFCellStyle style = workbook.createCellStyle();
//设置底边框;
style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
//设置底边框颜色;
style.setBottomBorderColor(HSSFColor.BLACK.index);
//设置左边框;
style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
//设置左边框颜色;
style.setLeftBorderColor(HSSFColor.BLACK.index);
//设置右边框;
style.setBorderRight(HSSFCellStyle.BORDER_THIN);
//设置右边框颜色;
style.setRightBorderColor(HSSFColor.BLACK.index);
//设置顶边框;
style.setBorderTop(HSSFCellStyle.BORDER_THIN);
//设置顶边框颜色;
style.setTopBorderColor(HSSFColor.BLACK.index);
//在样式用应用设置的字体;
/* style.setFillBackgroundColor(IndexedColors. GREY_25_PERCENT.index);// 设置背景颜色
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);*/
/* style.setFillBackgroundColor(IndexedColors. SKY_BLUE.index);// 设置背景颜色
style.setFillPattern(HSSFCellStyle.FINE_DOTS );*/
style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);//设置前景填充样式
style.setFillForegroundColor(IndexedColors. GREY_25_PERCENT.index);//前景填充色
style.setFont(font);
//设置自动换行;
style.setWrapText(false);
//设置水平对齐的样式为左对齐;
style.setAlignment(HSSFCellStyle.ALIGN_LEFT);
//设置垂直对齐的样式为居中对齐;
style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
return style;
}
}

本文介绍了使用Apache POI在Java中导出Excel时遇到的背景色设置问题,包括自定义颜色、背景色全黑的解决方法以及如何指定列添加背景色。关键在于设置填充样式为SOLID_FOREGROUND,并使用setFillForegroundColor方法来设置颜色。
1477

被折叠的 条评论
为什么被折叠?



