原 easyexcel(十四):导出excel自定义RGB颜色
版权声明:本文为博主原创文章,请尊重他人的劳动成果,转载请附上原文出处链接和本声明。
本文链接:https://www.91mszl.com/zhangwuji/article/details/1448
需求:由于客户的要求比较高,使用excel自带的60多种颜色,显然已经无法满足要求,这时我们就需要自定义RGB来实现了。这里只贴出了关键性的代码。
@Override
public void selectWordCloudDownLoad(HttpServletResponse response, WordCloudDownLoadVO pv) throws IOException {
List<WordCloudDownLoadDTO> dataList=productCommentMapper.selectWordCloudDownLoad(pv);
String wordCloudName=WordCloudTypeEnum.getValue(pv.getWordCloudType());
String fileName=URLEncoder.encode(wordCloudName, "UTF-8")+"-"+System.currentTimeMillis()+".xlsx"; // 这里URLEncoder.encode可以防止中文乱码
response.reset();
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setCharacterEncoding("utf-8");
response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName);
OutputStream os=response.getOutputStream();
EasyExcel.write(os, WordCloudDownLoadDTO.class)
.registerWriteHandler(new CustomHeadWriteHandler())
.sheet(ProductMsgUtils.SHEET_NAME_WORD_CLOUD).doWrite(dataList);
}
package com.mszl.utils;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.util.StyleUtil;
import com.alibaba.excel.write.style.AbstractCellStyleStrategy;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFColor;
import org.apache.poi.xssf.usermodel.XSSFFont;
public class CustomHeadWriteHandler extends AbstractCellStyleStrategy {
private XSSFCellStyle headCellStyle;
// 表头
@Override
protected void initCellStyle(Workbook workbook) {
// 设置样式
headCellStyle = (XSSFCellStyle) StyleUtil.buildHeadCellStyle(workbook, null);
headCellStyle.setAlignment(HorizontalAlignment.CENTER);
headCellStyle.setFillForegroundColor(IndexedColors.WHITE.getIndex());
headCellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
// 设置字体
Font font=workbook.createFont();
font.setFontName("微软雅黑");
font.setBold(true);
font.setFontHeightInPoints((short) 14);
XSSFFont xssfFont = (XSSFFont) font;
xssfFont.setColor(new XSSFColor(new java.awt.Color(120, 57, 167))); // 自定义RGB
headCellStyle.setFont(font);
}
@Override
protected void setHeadCellStyle(Cell cell, Head head, Integer integer) {
cell.setCellStyle(headCellStyle);
}
// 内容
@Override
protected void setContentCellStyle(Cell cell, Head head, Integer integer) {
// 设置样式
Workbook workbook=cell.getSheet().getWorkbook();
CellStyle contentStyle = workbook.createCellStyle();
contentStyle.setWrapText(true); // 自动换行
contentStyle.setAlignment(HorizontalAlignment.CENTER); // 水平居中
contentStyle.setVerticalAlignment(VerticalAlignment.CENTER); // 垂直居中
// 设置字体
Font font=workbook.createFont();
font.setFontName("微软雅黑");
font.setFontHeightInPoints((short) 14);
contentStyle.setFont(font);
cell.setCellStyle(contentStyle);
}
}
2023-07-28 17:04:54 阅读(1127)
名师出品,必属精品 https://www.91mszl.com
博主信息