91名师指路-头部
91名师指路

easyexcel(十四):导出excel自定义RGB颜色

由于某些原因,现在不支持支付宝支付,如需要购买源码请加博主微信进行购买,微信号:13248254750

需求:由于客户的要求比较高,使用excel自带的60多种颜色,显然已经无法满足要求,这时我们就需要自定义RGB来实现了。这里只贴出了关键性的代码。


一:service代码

@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);
}


二:CustomHeadWriteHandler

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     阅读(1128)

名师出品,必属精品    https://www.91mszl.com

联系博主    
用户登录遮罩层
x

账号登录

91名师指路-底部