首页 > 其他分享 >easyexcel导出头部样式设置,多个tab导出,头部自定义RGB颜色

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

时间:2024-11-30 17:38:06浏览次数:9  
标签:cellData 自定义 excel 导出 alibaba 头部 new import com

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

 

标签:cellData,自定义,excel,导出,alibaba,头部,new,import,com
From: https://www.cnblogs.com/liran123/p/18578654

相关文章

  • Unity Mask原理及自定义遮罩
    主要内容StencilBuffer是什么?自定义Shader来实现遮罩UnityMask的原理1.什么是StencilBufferGPU在渲染前会为每个像素点分配一个1字节(8位)大小的内存区域,即StencilBuffer。在决定是否要渲染某个像素点之前,会将它当前的StencilBuffer的值与某个参考值(stencilID)进行指定......
  • gofiber: 用go-playground/validator校验参数,自定义错误信息
    一,go-playground/validator官方代码地址https://github.com/go-playground/validator二,安装$goget-ugithub.com/go-playground/validator/v10go:downloadinggithub.com/go-playground/validator/v10v10.23.0go:downloadinggithub.com/gabriel-vasile/mimetypev1.4.......
  • ios短视频开发,自定义缓存策略的实现
    ios短视频开发,自定义缓存策略的实现缓存所占用的空间往往会成为迫使用户卸载应用的最后一根稻草。开发者不能无上限对音视频资源进行缓存,通常的维护手法是通过限制空间大小,比如,用户通常可以接受视频类应用有1G左右的缓存空间,即时通信类应用也许会更大些。因此在ios短视频开发......
  • uni-app vue3 获取 package.json 自定义环境变量
    一、初始化项目 二、添加 package.json 文件(必须)注意:文件里面不要写备注{ "uni-app":{ "scripts":{ "dev":{ "title":"开发版", "env":{ "ENV_TYPE":"dev", "UNI_PLATFORM&q......
  • 头部设置meta也可以做到自适应为啥还要用rem?
    你问的是一个很好的问题!虽然<metaname="viewport"content="width=device-width,initial-scale=1.0">可以使网页在不同设备上自适应,但这与使用rem单位是解决不同问题的两种不同技术,它们通常结合使用以获得最佳效果。metaviewport的作用:控制视口宽度:它主要控制视口的......
  • vue3自定义指令实现截图
    依赖:•使用html2canvas(需要先安装:npminstallhtml2canvas)。绑定事件:•在目标DOM上绑定click事件。截图逻辑:•点击后调用html2canvas截取目标元素的截图。•使用Canvas的toDataURL()方法生成Base64图片。保存文件:•创建一个a标签,通过downloa......
  • 使用Java导出excel内包含图片
    功能使用点最近公司需要开发一个数据表格导出excel的功能,普通的excel表格很好解决,网上有很多方法,下次写篇文章记录我的方法,但开发到有一个需求是excel是需要带图片的还是有些难度的,网上找了很多方案都无法适配,这里我记录下使用的方法。这里最后是在这篇文章上进行了优化,优化......
  • RUOYI参数验证异常处理及自定义注解触发验证抛出异常报错
    目录一.ruoyi与参数验证1.触发报错2.后端现象二.源码分析1.前端代码2.后端代码3.报错分析三.自定义函数注解1.NoNumber注解2.NoNumberMain校验器3.将注解添加进SysRole中4.前端&后端现象一.ruoyi与参数验证1.触发报错对参数验证的使用,从触发参数报错开始,首先对ru......
  • 使用XWPFTemplate进行java后端word模版导出
    1.pom引入poi-tl<dependency><groupId>com.deepoove</groupId><artifactId>poi-tl</artifactId><version>1.7.3</version></dependency> 2.word模版 3.业务代码......
  • 自定义一个WinForm个性化的TabControl
    系列文章目录第一章自定义一个WinForm异形按钮第二章自定义一个WinForm圆角文本框第三章自定义一个WinForm个性化的TabControl文章目录系列文章目录前言一、效果展示自定义TabControl效果展示二、TabControl自定义1.创建一个MyTabControl2.自定义并暴露出一些常......