java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Java EasyExcel导出sheet

Java EasyExcel实现导出多sheet并设置单元格样式

作者:penga

EasyExcel是一个基于Java的、快速、简洁、解决大文件内存溢出的Excel处理工具,下面我们就来学习一下EasyExcel如何实现导出多sheet并设置单元格样式吧

前言

最近在做项目时遇到了特殊的Excel导出需求,需要对不同sheet设置不同样式,但网上找了很多方法都有问题。在经历一段时间的爬坑之后,终于解决,于是写这篇文章把他分享出来。

EasyExcel简介

EasyExcel是一个基于Java的、快速、简洁、解决大文件内存溢出的Excel处理工具。他能让你在不用考虑性能、内存的等因素的情况下,快速完成Excel的读、写等功能。也是目前比较常用的Excel处理工具。

关于如何读取和写入Excel文件,官网教程已经很全面,这里不做过多赘述。

需求

假设我们遇到了这样一个需求:

现在要导出一个数码产品的报表,有手机和电脑两大类,需要在表头统计总价、均价、最高价、最低价,并需要按指标对数据进行特殊处理。

手机:

电脑:

开始

导入依赖

SpringBoot 依赖自行导入

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>easyexcel</artifactId>
    <version>3.3.2</version>
</dependency>

<!-- hutool 工具集,为了构造模拟数据,具体项目请根据实际情况引入 -->
<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-all</artifactId>
    <version>5.8.22</version>
</dependency>

接口

注:为了阅读简洁,这里简化了部分代码

/**
 * 导出Excel 接口
 *
 * @param response
 */
@PostMapping("export")
public void exportExcel(HttpServletResponse response) {
    digitalProductService.exportExcel(response);
}

服务实现类

首先模拟一部分数据

package com.penga.demo.service.impl;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.penga.demo.service.IDigitalProductService;
import com.penga.demo.util.DigitalProductCellWriteHandler;
import com.penga.demo.util.EasyExcelUtils;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class DigitalProductServiceImpl implements IDigitalProductService {

    @Override
    public void exportExcel(HttpServletResponse response) {
        // 初始化多个sheet
        List<String> sheetNames = ListUtil.toList("手机", "电脑");
        // 初始化数据集
        List<List<List<Object>>> dataLists = getDatas();
        // 统计数据
        List<BigDecimal> phonePriceList = dataLists.get(0).stream().map(dl -> Convert.toBigDecimal(dl.get(3))).collect(Collectors.toList());
        List<BigDecimal> pcPriceList = dataLists.get(1).stream().map(dl -> Convert.toBigDecimal(dl.get(2))).collect(Collectors.toList());
        String phoneTotalHeader = getTotalHeader(phonePriceList);
        String pcTotalHeader = getTotalHeader(pcPriceList);
        // 初始化每个sheet里面的header
        List<List<List<String>>> headerLists = getHeaders(phoneTotalHeader, pcTotalHeader);
        EasyExcelUtils.writeExcelSheets(response, "数码产品报表", sheetNames, headerLists, dataLists, new DigitalProductCellWriteHandler());
    }

    private List<List<List<String>>> getHeaders(String phoneTotalHeader, String pcTotalHeader) {
        String phoneTitle = "手机-统计报表";
        String pcTitle = "电脑-统计报表";
        List<List<List<String>>> headerLists = new ArrayList<>();
        List<List<String>> headerList1 = new ArrayList<>();
        headerList1.add(ListUtil.toList(phoneTitle, phoneTotalHeader, "序号"));
        headerList1.add(ListUtil.toList(phoneTitle, phoneTotalHeader, "型号"));
        headerList1.add(ListUtil.toList(phoneTitle, phoneTotalHeader, "上市日期"));
        headerList1.add(ListUtil.toList(phoneTitle, phoneTotalHeader, "价格"));
        headerList1.add(ListUtil.toList(phoneTitle, phoneTotalHeader, "CPU"));
        headerList1.add(ListUtil.toList(phoneTitle, phoneTotalHeader, "RAM容量"));
        headerList1.add(ListUtil.toList(phoneTitle, phoneTotalHeader, "ROM容量"));
        List<List<String>> headerList2 = new ArrayList<>();
        headerList2.add(ListUtil.toList(pcTitle, pcTotalHeader, "序号"));
        headerList2.add(ListUtil.toList(pcTitle, pcTotalHeader, "配置"));
        headerList2.add(ListUtil.toList(pcTitle, pcTotalHeader, "价格"));
        headerList2.add(ListUtil.toList(pcTitle, pcTotalHeader, "CPU"));
        headerList2.add(ListUtil.toList(pcTitle, pcTotalHeader, "显卡"));
        headerList2.add(ListUtil.toList(pcTitle, pcTotalHeader, "内存"));
        headerList2.add(ListUtil.toList(pcTitle, pcTotalHeader, "硬盘容量"));
        headerLists.add(headerList1);
        headerLists.add(headerList2);
        return headerLists;
    }

    private String getTotalHeader(List<BigDecimal> priceList) {
        BigDecimal sum = priceList.stream().reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal avg = sum.divide(new BigDecimal(priceList.size()), 2, RoundingMode.HALF_UP);
        BigDecimal max = priceList.stream().max(BigDecimal::compareTo).orElse(BigDecimal.ZERO);
        BigDecimal min = priceList.stream().min(BigDecimal::compareTo).orElse(BigDecimal.ZERO);
        return StrUtil.format("总价:{}  均价:{}\n最高价:{}  最低价:{}", sum, avg, max, min);
    }

    private List<List<List<Object>>> getDatas() {
        List<List<List<Object>>> dataLists = new ArrayList<>();
        // dataList 的顺序一定要与 headerList 的顺序一一对应
        List<List<Object>> dataList1 = new ArrayList<>();
        dataList1.add(ListUtil.toList(1, "iQOO 12 Pro", "2023年11月7日", new BigDecimal("4999.00"), "高通 骁龙8 Gen3", "16GB", "256GB"));
        dataList1.add(ListUtil.toList(2, "小米14 Pro", "2023年10月31日", new BigDecimal("5499.00"), "高通 骁龙8 Gen3", "16GB", "512GB"));
        dataList1.add(ListUtil.toList(3, "HUAWEI Mate 60 Pro", "2023年8月29日", new BigDecimal("6999.00"), "海思 麒麟 9000s", "12GB", "512GB"));
        dataList1.add(ListUtil.toList(4, "苹果iPhone 15 Pro", "2023年09月22日", new BigDecimal("10999.00"), "苹果 A17 Pro", "8GB", "256GB"));
        dataList1.add(ListUtil.toList(5, "vivo X90s", "2023年06月30日", new BigDecimal("4099.00"), "联发科 天玑9200+", "12GB", "512GB"));
        dataLists.add(dataList1);
        List<List<Object>> dataList2 = new ArrayList<>();
        dataList2.add(ListUtil.toList(1, "配置1", new BigDecimal("5199.00"), "Intel 酷睿 i5 13400F", "RTX 4060", "16GB", "固态硬盘 1TB"));
        dataList2.add(ListUtil.toList(2, "配置2", new BigDecimal("17599.00"), "Intel 酷睿 i9 14900KF", "RTX 4080", "32GB", "机械硬盘 1TB"));
        dataList2.add(ListUtil.toList(3, "配置3", new BigDecimal("30999.00"), "Intel 酷睿 i9 14900KF", "RTX 4090", "32GB", "固态硬盘 2TB"));
        dataLists.add(dataList2);
        return dataLists;
    }
}

这里针对几个list进行说明

Excel导出工具

package com.penga.demo.util;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.builder.ExcelWriterSheetBuilder;
import com.alibaba.excel.write.handler.WriteHandler;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import org.apache.poi.ss.usermodel.*;
import org.springframework.http.MediaType;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

public class EasyExcelUtils {

    /**
     * @param response     返回
     * @param fileName     文件名
     * @param sheetNames   sheet集合
     * @param headerLists  表头集合
     * @param dataLists    数据集合
     * @param writeHandler 自定义样式
     */
    public static void writeExcelSheets(HttpServletResponse response, String fileName, List<String> sheetNames,
                                        List<List<List<String>>> headerLists, List<List<List<Object>>> dataLists, WriteHandler writeHandler) {
        ServletOutputStream out = null;
        try {
            out = getOut(response, fileName);
            sheetNames = sheetNames.stream().distinct().collect(Collectors.toList());
            int num = sheetNames.size();

            // 设置基础样式
            HorizontalCellStyleStrategy horizontalCellStyleStrategy = new HorizontalCellStyleStrategy(getHeadStyle(), getContentStyle());
            ExcelWriter excelWriter = EasyExcel.write(out).build();
            for (int i = 0; i < num; i++) {
                ExcelWriterSheetBuilder sheetBuilder = EasyExcel.writerSheet(i, sheetNames.get(i)).head(headerLists.get(i))
                        // 自动列宽(按实际情况加入)
                        .registerWriteHandler(new CustomHandler())
                        .registerWriteHandler(horizontalCellStyleStrategy);
                if (Objects.nonNull(writeHandler)) {
                    // 自定义样式设置
                    sheetBuilder.registerWriteHandler(writeHandler);
                }
                WriteSheet writeSheet = sheetBuilder.build();
                if (CollectionUtil.isEmpty(dataLists)) {
                    excelWriter.write(new ArrayList<>(), writeSheet);
                } else {
                    excelWriter.write(dataLists.get(i), writeSheet);
                }
            }
            excelWriter.finish();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (Objects.nonNull(out)) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private static ServletOutputStream getOut(HttpServletResponse response, String fileName) throws Exception {
        fileName = fileName + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + ExcelTypeEnum.XLSX.getValue();
        setAttachmentResponseHeader(response, fileName);
        response.setCharacterEncoding("utf-8");
        response.setContentType(MediaType.MULTIPART_FORM_DATA_VALUE);
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        return response.getOutputStream();
    }

    /**
     * 下载文件名重新编码
     *
     * @param response     响应对象
     * @param realFileName 真实文件名
     * @return
     */
    public static void setAttachmentResponseHeader(HttpServletResponse response, String realFileName) throws UnsupportedEncodingException {
        String percentEncodedFileName = percentEncode(realFileName);
        String contentDispositionValue = "attachment; filename=" + percentEncodedFileName + ";filename*=utf-8''" + percentEncodedFileName;
        response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
        response.setHeader("Content-Disposition", contentDispositionValue);
    }

    /**
     * 百分号编码工具方法
     *
     * @param s  需要百分号编码的字符串
     * @return   百分号编码后的字符串
     */
    public static String percentEncode(String s) throws UnsupportedEncodingException {
        String encode = URLEncoder.encode(s, StandardCharsets.UTF_8.toString());
        return encode.replaceAll("\+", "%20");
    }

    /**
     * 头部样式
     */
    private static WriteCellStyle getHeadStyle() {
        // 头的策略
        WriteCellStyle headWriteCellStyle = new WriteCellStyle();
        // 背景颜色
        headWriteCellStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
        headWriteCellStyle.setFillPatternType(FillPatternType.SOLID_FOREGROUND);

        // 字体
        WriteFont headWriteFont = new WriteFont();
        //设置字体名字
        headWriteFont.setFontName("微软雅黑");
        //设置字体大小
        headWriteFont.setFontHeightInPoints((short) 10);
        //字体加粗
        headWriteFont.setBold(false);
        //在样式用应用设置的字体
        headWriteCellStyle.setWriteFont(headWriteFont);

        // 边框样式
        setBorderStyle(headWriteCellStyle);

        //设置自动换行
        headWriteCellStyle.setWrapped(true);

        //设置水平对齐的样式为居中对齐
        headWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
        //设置垂直对齐的样式为居中对齐
        headWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);

        //设置文本收缩至合适
        //        headWriteCellStyle.setShrinkToFit(true);

        return headWriteCellStyle;
    }

    /**
     * 内容样式
     */
    private static WriteCellStyle getContentStyle() {
        // 内容的策略
        WriteCellStyle contentWriteCellStyle = new WriteCellStyle();

        // 背景白色
        // 这里需要指定 FillPatternType 为FillPatternType.SOLID_FOREGROUND 不然无法显示背景颜色.头默认了 FillPatternType所以可以不指定
        contentWriteCellStyle.setFillForegroundColor(IndexedColors.WHITE.getIndex());
        contentWriteCellStyle.setFillPatternType(FillPatternType.SOLID_FOREGROUND);

        // 设置字体
        WriteFont contentWriteFont = new WriteFont();
        //设置字体大小
        contentWriteFont.setFontHeightInPoints((short) 10);
        //设置字体名字
        contentWriteFont.setFontName("宋体");
        //在样式用应用设置的字体
        contentWriteCellStyle.setWriteFont(contentWriteFont);

        //设置样式
        setBorderStyle(contentWriteCellStyle);

        // 水平居中
        contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
        // 垂直居中
        contentWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        //设置自动换行
        contentWriteCellStyle.setWrapped(true);

        //设置单元格格式是:文本格式,方式长数字文本科学计数法
//        contentWriteCellStyle.setDataFormatData();

        //设置文本收缩至合适
        // contentWriteCellStyle.setShrinkToFit(true);

        return contentWriteCellStyle;
    }

    /**
     * 边框样式
     */
    private static void setBorderStyle(WriteCellStyle cellStyle) {
        //设置底边框
        cellStyle.setBorderBottom(BorderStyle.THIN);
        //设置底边框颜色
        cellStyle.setBottomBorderColor(IndexedColors.BLACK1.getIndex());
        //设置左边框
        cellStyle.setBorderLeft(BorderStyle.THIN);
        //设置左边框颜色
        cellStyle.setLeftBorderColor(IndexedColors.BLACK1.getIndex());
        //设置右边框
        cellStyle.setBorderRight(BorderStyle.THIN);
        //设置右边框颜色
        cellStyle.setRightBorderColor(IndexedColors.BLACK1.getIndex());
        //设置顶边框
        cellStyle.setBorderTop(BorderStyle.THIN);
        //设置顶边框颜色
        cellStyle.setTopBorderColor(IndexedColors.BLACK1.getIndex());
    }
}

自定义样式

如果要设置其他样式,可以在评论区提出来,或阅读源码。

package com.penga.demo.util;

import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import org.apache.poi.ss.usermodel.*;

import java.util.List;

public class DigitalProductCellWriteHandler implements CellWriteHandler {

    @Override
    public void afterCellDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, List<WriteCellData<?>> cellDataList, 
                                Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {
        int rowIndex = cell.getRowIndex();
        int columnIndex = cell.getColumnIndex();
        String sheetName = cell.getSheet().getSheetName();
        if (rowIndex == 1 && columnIndex == 0) {
            // 设置表头统计的样式,由于单元格是合并的,只设置第一列就行了
            setTotalStyle(writeSheetHolder, cellDataList, cell);
            return;
        }
        if (!isHead) {
            // 内容样式处理
            Workbook workbook = cell.getSheet().getWorkbook();
            if (sheetName.equals("手机")) {
                // 判断是否为”手机“sheet
                if (columnIndex == 3) {
                    // 判断价格
                    // 注意,这里的 cell.get**Value 有多个方法,一定要准确,否则会报错,报错后不会再进入这个拦截器,直接导出了
                    // 如果无法准确判断应该用哪个 getValue,可以 debug 测试
                    double value = cell.getNumericCellValue();
                    if (value > 5000.00) {
                        // 字体样式改为红色
                        CellStyle cellStyle = getContentCellStyle(workbook, IndexedColors.WHITE.getIndex(), IndexedColors.RED.getIndex());
                        //设置当前单元格样式
                        cell.setCellStyle(cellStyle);
                        // 这里要把 WriteCellData的样式清空
                        // 不然后面还有一个拦截器 FillStyleCellWriteHandler 默认会将 WriteCellStyle 设置到cell里面去 会导致自己设置的不一样
                        cellDataList.get(0).setWriteCellStyle(null);
                    }
                } else if (columnIndex == 4) {
                    // 判断CPU
                    String value = cell.getStringCellValue();
                    if (value.contains("骁龙8 Gen3")) {
                        // 背景改为黄色
                        CellStyle cellStyle = getContentCellStyle(workbook, IndexedColors.YELLOW.getIndex(), IndexedColors.BLACK.getIndex());
                        cell.setCellStyle(cellStyle);
                        cellDataList.get(0).setWriteCellStyle(null);
                    }
                }
            } else {
                // ”电脑“sheet
                if (columnIndex == 2) {
                    // 判断价格
                    double value = cell.getNumericCellValue();
                    if (value > 10000.00) {
                        // 字体样式改为红色
                        CellStyle cellStyle = getContentCellStyle(workbook, IndexedColors.WHITE.getIndex(), IndexedColors.RED.getIndex());
                        cell.setCellStyle(cellStyle);
                        cellDataList.get(0).setWriteCellStyle(null);
                    }
                } else if (columnIndex == 4) {
                    String value = cell.getStringCellValue();
                    if (value.contains("RTX 4090")) {
                        // 背景改为蓝色
                        CellStyle cellStyle = getContentCellStyle(workbook, IndexedColors.LIGHT_BLUE.getIndex(), IndexedColors.BLACK.getIndex());
                        cell.setCellStyle(cellStyle);
                        cellDataList.get(0).setWriteCellStyle(null);
                    }
                }
            }
        }
    }

    private CellStyle getContentCellStyle(Workbook workbook, short ffColorIndex, short fontColorIndex) {
        // 单元格策略
        CellStyle cellStyle = workbook.createCellStyle();
        // 设置背景颜色
        cellStyle.setFillForegroundColor(ffColorIndex);
        cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        // 设置垂直居中为居中对齐
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        // 设置左右对齐为居中对齐
        cellStyle.setAlignment(HorizontalAlignment.CENTER);
        // 自动换行
        cellStyle.setWrapText(true);
        // 设置边框
        setBorderStyle(cellStyle);
        // 字体
        Font font = workbook.createFont();
        //设置字体名字
        font.setFontName("宋体");
        //设置字体大小
        font.setFontHeightInPoints((short) 10);
        // 设置字体颜色
        font.setColor(fontColorIndex);
        //字体加粗
        font.setBold(false);
        //在样式用应用设置的字体
        cellStyle.setFont(font);
        return cellStyle;
    }

    private void setTotalStyle(WriteSheetHolder writeSheetHolder, List<WriteCellData<?>> cellDataList, Cell cell) {
        Workbook workbook = cell.getSheet().getWorkbook();
        //设置行高
        writeSheetHolder.getSheet().getRow(cell.getRowIndex()).setHeight((short) (1.4 * 256 * 2));
        // 单元格策略
        CellStyle cellStyle = workbook.createCellStyle();
        // 设置背景颜色灰色
        cellStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
        cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        // 设置垂直居中为居中对齐
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        // 设置左右对齐为靠右对齐
        cellStyle.setAlignment(HorizontalAlignment.RIGHT);
        // 自动换行
        cellStyle.setWrapText(true);
        // 设置边框
        setBorderStyle(cellStyle);
        // 字体
        Font font = workbook.createFont();
        //设置字体名字
        font.setFontName("微软雅黑");
        //设置字体大小
        font.setFontHeightInPoints((short) 10);
        //字体加粗
        font.setBold(false);
        //在样式用应用设置的字体
        cellStyle.setFont(font);
        //设置当前单元格样式
        cell.setCellStyle(cellStyle);
        // 这里要把 WriteCellData的样式清空
        // 不然后面还有一个拦截器 FillStyleCellWriteHandler 默认会将 WriteCellStyle 设置到cell里面去 会导致自己设置的不一样
        cellDataList.get(0).setWriteCellStyle(null);
    }

    /**
     * 边框样式
     */
    private static void setBorderStyle(CellStyle cellStyle) {
        //设置底边框
        cellStyle.setBorderBottom(BorderStyle.THIN);
        //设置底边框颜色
        cellStyle.setBottomBorderColor(IndexedColors.BLACK1.getIndex());
        //设置左边框
        cellStyle.setBorderLeft(BorderStyle.THIN);
        //设置左边框颜色
        cellStyle.setLeftBorderColor(IndexedColors.BLACK1.getIndex());
        //设置右边框
        cellStyle.setBorderRight(BorderStyle.THIN);
        //设置右边框颜色
        cellStyle.setRightBorderColor(IndexedColors.BLACK1.getIndex());
        //设置顶边框
        cellStyle.setBorderTop(BorderStyle.THIN);
        //设置顶边框颜色
        cellStyle.setTopBorderColor(IndexedColors.BLACK1.getIndex());
    }
}

设置自定义样式后,一定要将原来的样式清空(cellDataList.get(0).setWriteCellStyle(null);),否则会导致自定义的样式设置不进去

自动列宽

这个方法也不太准确,有的情况下列会特别宽,如果有更好的方法,欢迎在评论区指出

package com.penga.demo.util;
import cn.hutool.core.collection.CollectionUtil;
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.poi.ss.usermodel.Cell;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class CustomHandler extends AbstractColumnWidthStyleStrategy {
    /**
     * 最大列宽
     */
    private static final int MAX_COLUMN_WIDTH = 255;
    private static final Map<Integer, Map<Integer, Integer>> CACHE = new HashMap<>(8);
    public CustomHandler() {
    }
    @Override
    protected void setColumnWidth(WriteSheetHolder writeSheetHolder, List<WriteCellData<?>> cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {
        boolean needSetWidth = isHead || !CollectionUtil.isEmpty(cellDataList);
        if (isHead) {
            // 如果不是最后一个表头,则不改变列宽
            List<String> headNameList = head.getHeadNameList();
            if (CollectionUtil.isNotEmpty(headNameList)) {
                int size = headNameList.size();
                if (!cell.getStringCellValue().equals(headNameList.get(size - 1))) {
                    return;
                }
            }
        }
        if (needSetWidth) {
            Map<Integer, Integer> maxColumnWidthMap = CACHE.computeIfAbsent(writeSheetHolder.getSheetNo(), k -> new HashMap<>(16));
            Integer columnWidth = this.dataLength(cellDataList, cell, isHead);
            if (columnWidth >= 0) {
                if (columnWidth > MAX_COLUMN_WIDTH) {
                    columnWidth = MAX_COLUMN_WIDTH;
                }
                Integer maxColumnWidth = maxColumnWidthMap.get(cell.getColumnIndex());
                if (maxColumnWidth == null || columnWidth > maxColumnWidth) {
                    maxColumnWidthMap.put(cell.getColumnIndex(), columnWidth);
                    writeSheetHolder.getSheet().setColumnWidth(cell.getColumnIndex(), columnWidth * 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;
            } else {
                switch (type) {
                    case STRING:
                        return cellData.getStringValue().getBytes().length;
                    case BOOLEAN:
                        return cellData.getBooleanValue().toString().getBytes().length;
                    case NUMBER:
                        return cellData.getNumberValue().toString().getBytes().length;
                    case DATE:
                        return cellData.getDateValue().toString().getBytes().length;
                    default:
                        return -1;
                }
            }
        }
    }
}

导出

使用API调试工具发送请求:

最终的导出效果如下:

以上就是Java EasyExcel实现导出多sheet并设置单元格样式的详细内容,更多关于Java EasyExcel导出sheet的资料请关注脚本之家其它相关文章!

您可能感兴趣的文章:
阅读全文