easyexcel导出头部样式设置,多个tab导出,头部自定义RGB颜色

alibaba easyexcel版本 3.0.5, poi版本 4.1.2 ,导出头部样式设置,多个tab导出,头部自定义RGB颜色

 

效果,头部三行,三个tab

 

 

下面贴出代码:

package com.alpha.erp.dto.accounts;

import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.write.handler.context.CellWriteHandlerContext;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.AbstractCellStyleStrategy;
import com.alibaba.excel.write.style.AbstractVerticalCellStyleStrategy;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.DefaultIndexedColorMap;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFColor;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.util.Objects;

/**
 * lr l
 */
public class AccountsCellStyleWrapped extends AbstractCellStyleStrategy {

    @Override
    protected void setHeadCellStyle(CellWriteHandlerContext context) {
        WriteCellData<?> cellData = context.getFirstCellData();
        CellStyle originCellStyle = cellData.getOriginCellStyle();
        if (Objects.isNull(originCellStyle)) {
            originCellStyle = context.getWriteWorkbookHolder().getWorkbook().createCellStyle();
        }
        // 设置背景颜色
        originCellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        WriteCellStyle writeCellStyle = cellData.getWriteCellStyle();
        writeCellStyle.setFillForegroundColor(null);
        if (context.getRowIndex() == 1) {
            ((XSSFCellStyle) originCellStyle).setFillForegroundColor(new XSSFColor(new java.awt.Color(237, 237, 237), new DefaultIndexedColorMap()));
        } else {
            ((XSSFCellStyle) originCellStyle).setFillForegroundColor(new XSSFColor(new java.awt.Color(217, 226, 243), new DefaultIndexedColorMap()));
        }
        // 重点!!! 必须设置OriginCellStyle
        cellData.setOriginCellStyle(originCellStyle);
        WriteFont font = new WriteFont();
        font.setBold(true);
        font.setFontHeightInPoints((short) 14);
        writeCellStyle.setWriteFont(font);
    }


    @Override
    protected void setContentCellStyle(CellWriteHandlerContext context) {
        WriteCellData<?> cellData = context.getFirstCellData();
        CellStyle originCellStyle = cellData.getOriginCellStyle();
        if (Objects.isNull(originCellStyle)) {
            originCellStyle = context.getWriteWorkbookHolder().getWorkbook().createCellStyle();
        }
        // 设置背景颜色
        originCellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        WriteCellStyle writeCellStyle = cellData.getWriteCellStyle();
        writeCellStyle.setWrapped(true);
        WriteFont font = new WriteFont();
        font.setBold(false);
        font.setFontHeightInPoints((short) 12);
        writeCellStyle.setWriteFont(font);
    }
}
package com.orderplus.core.util.excel;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.style.column.AbstractColumnWidthStyleStrategy;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Cell;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * lr
 */
public class ExcelCellWidthWrappedStyleUtils extends AbstractColumnWidthStyleStrategy {

    private static final int MAX_COLUMN_WIDTH = 255;
    private Map<Integer, Map<Integer, Integer>> CACHE = new HashMap<>(8);

    @Override
    protected void setColumnWidth(WriteSheetHolder writeSheetHolder, List<WriteCellData<?>> list, Cell cell, Head head, Integer integer, Boolean isHead) {

        boolean needSetWidth = isHead || !CollUtil.isEmpty(list);

        if (needSetWidth) {
            Map<Integer, Integer> maxColumnWidthMap = CACHE.computeIfAbsent(writeSheetHolder.getSheetNo(), k -> new HashMap<>(16));

            Integer columnWidth = this.dataLength(list, cell, isHead);

            if (columnWidth >= 0) {
                if (columnWidth > 255) {
                    columnWidth = 255;
                }

                Integer maxColumnWidth = maxColumnWidthMap.get(cell.getColumnIndex());

                if (maxColumnWidth == null || columnWidth > maxColumnWidth) {
                    maxColumnWidthMap.put(cell.getColumnIndex(), columnWidth);
                    writeSheetHolder.getSheet().setColumnWidth(cell.getColumnIndex(), columnWidth * 256);
                }
                if (CollUtil.isNotEmpty(writeSheetHolder.getExcelWriteHeadProperty().getHeadMap())) {
                    Map<Integer, Head> headMap = writeSheetHolder.getExcelWriteHeadProperty().getHeadMap();
                    Head headRw = headMap.get(cell.getColumnIndex());
                    if(headRw==null ||headRw.getColumnWidthProperty()==null){
                        return;
                    }
                    Integer width = headRw.getColumnWidthProperty().getWidth();
                    if (width != null) {
                        maxColumnWidthMap.put(cell.getColumnIndex(), width);
                        writeSheetHolder.getSheet().setColumnWidth(cell.getColumnIndex(), width * 256);
                    }
                }
            }
        }

    }

    private Integer dataLength(List<WriteCellData<?>> cellDataList, Cell cell, Boolean isHead) {
        if (isHead) {
            return cell.getStringCellValue().getBytes().length;
        } else {
            WriteCellData cellData = cellDataList.get(0);
            CellDataTypeEnum type = cellData.getType();
            if (type == null) {
                return -1;
            }

            switch (type) {
                case STRING:
                    if (cellData.getStringValue().contains("\n")) {
                        return StringUtils.substringBefore(cellData.getStringValue(), "\n").getBytes().length;
                    }
                    return cellData.getStringValue().getBytes().length + 1;
                case BOOLEAN:
                    return cellData.getBooleanValue().toString().getBytes().length;
                case NUMBER:
                    return cellData.getNumberValue().toString().getBytes().length;
                default:
                    return -1;
            }
        }
    }
}

 

 

上面两个是样式和宽度设置类

private void exportReportNew(List<ErpSupplierAccountsInfoListKaVo> productPutWatchListVos, HttpServletResponse response) throws IOException {
        String fileName = "报告导出";
        fileName = URLEncoder.encode(fileName, "UTF-8");
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ";filename*=utf-8''" + fileName + ".xlsx");
        ServletOutputStream outputStream = response.getOutputStream();
        ExcelWriter excelWriter = null;
        try {

            excelWriter = EasyExcel.write(outputStream)
                    .excelType(ExcelTypeEnum.XLSX)  // 设置文件类型为 XLSX
                    .registerWriteHandler(new AccountsCellStyleWrapped())
                    .registerWriteHandler(new ExcelCellWidthWrappedStyleUtils())
                    .build();
            WriteSheet sheet1 = EasyExcel.writerSheet("月欠款及还款计划明细")
                    .head(AccountInfoReportExcel.class)
                    .build();
            excelWriter.write(buildInfoExcelData(productPutWatchListVos), sheet1);
            WriteSheet sheet2 = EasyExcel.writerSheet("月分销欠款风险")
                    .head(AccountInfoCustomerReportExcel.class)
                    .build();
            excelWriter.write(buildCustomerExcelData(productPutWatchListVos), sheet2);
            WriteSheet sheet3 = EasyExcel.writerSheet("月供应商应收")
                    .head(AccountInfoSupplierReportExcel.class)
                    .build();
            excelWriter.write(buildSupplierExcelData(productPutWatchListVos), sheet3);
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            if (excelWriter != null) {
                excelWriter.finish();
            }
            outputStream.flush();
            outputStream.close();
        }
    }

 

posted @ 2024-11-30 17:20  _Phoenix  阅读(51)  评论(0编辑  收藏  举报