easypoi一对多,合并单元格,并且根据内容自适应行高

Posted 符华-

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了easypoi一对多,合并单元格,并且根据内容自适应行高相关的知识,希望对你有一定的参考价值。

记录一下

效果

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

一、引入依赖

<dependency>
	<groupId>cn.afterturn</groupId>
	<artifactId>easypoi-spring-boot-starter</artifactId>
	<version>4.1.3</version>
</dependency>

二、实体类

import cn.afterturn.easypoi.excel.annotation.Excel;
import cn.afterturn.easypoi.excel.annotation.ExcelCollection;
import lombok.Data;
import java.util.List;

@Data
public class TestExportMainVo {
    @Excel(name = "项目",width = 20,needMerge = true)
    private String project;

    @ExcelCollection(name = "")
    private List<TestExportSub1Vo> sub1VoList;

    public TestExportMainVo(String project, List<TestExportSub1Vo> sub1VoList) {
        this.project = project;
        this.sub1VoList = sub1VoList;
    }
}
@Data
public class TestExportSub1Vo {
    @Excel(name = "序号",width = 8,needMerge = true)
    private String sort;

    @Excel(name = "依据",width = 30,needMerge = true)
    private String basis;

    @ExcelCollection(name = "")
    private List<TestExportSub2Vo> sub2VoList;

    public TestExportSub1Vo(String sort, String basis, List<TestExportSub2Vo> sub2VoList) {
        this.sort = sort;
        this.basis = basis;
        this.sub2VoList = sub2VoList;
    }
}
@Data
public class TestExportSub2Vo {
    @Excel(name = "操作步骤",width = 60)
    private String step;

    @Excel(name = "条款",width = 12)
    private String clause;

    public TestExportSub2Vo(String step, String clause) {
        this.step = step;
        this.clause = clause;
    }
}

@Excel注解中,needMerge =true 用于合并单元格

三、excel工具类

1、样式工具类 ExcelExportStylerUitl

import cn.afterturn.easypoi.excel.entity.params.ExcelExportEntity;
import cn.afterturn.easypoi.excel.entity.params.ExcelForEachParams;
import cn.afterturn.easypoi.excel.export.styler.IExcelExportStyler;
import org.apache.poi.ss.usermodel.*;

/**
 * @author fuHua
 * @date 2021年05月27日 14:55
 */
public class ExcelExportStylerUitl implements IExcelExportStyler {

    private static final short STRING_FORMAT = (short) BuiltinFormats.getBuiltinFormat("TEXT");
    private static final short FONT_SIZE_TEN = 10;
    private static final short FONT_SIZE_ELEVEN = 11;
    private static final short FONT_SIZE_TWELVE = 12;
    /**
     * 大标题样式
     */
    private CellStyle headerStyle;
    /**
     * 每列标题样式
     */
    private CellStyle titleStyle;
    /**
     * 数据行样式
     */
    private CellStyle styles;

    public ExcelExportStylerUitl(Workbook workbook) {
        this.init(workbook);
    }

    /**
     * 初始化样式
     * @param workbook
     */
    private void init(Workbook workbook) {
        this.headerStyle = initHeaderStyle(workbook);
        this.titleStyle = initTitleStyle(workbook);
        this.styles = initStyles(workbook);
    }

    /**
     * 大标题样式
     * @param color
     * @return
     */
    @Override
    public CellStyle getHeaderStyle(short color) {
        return headerStyle;
    }

    /**
     * 每列标题样式
     * @param color
     * @return
     */
    @Override
    public CellStyle getTitleStyle(short color) {
        return titleStyle;
    }

    /**
     * 数据行样式
     * @param parity 可以用来表示奇偶行
     * @param entity 数据内容
     * @return 样式
     */
    @Override
    public CellStyle getStyles(boolean parity, ExcelExportEntity entity) {
        return styles;
    }

    /**
     * 获取样式方法
     * @param dataRow 数据行
     * @param obj     对象
     * @param data    数据
     */
    @Override
    public CellStyle getStyles(Cell cell, int dataRow, ExcelExportEntity entity, Object obj, Object data) {
        return getStyles(true, entity);
    }

    /**
     * 模板使用的样式设置
     */
    @Override
    public CellStyle getTemplateStyles(boolean isSingle, ExcelForEachParams excelForEachParams) {
        return null;
    }

    /**
     * 初始化--大标题样式
     * @param workbook
     * @return
     */
    private CellStyle initHeaderStyle(Workbook workbook) {
        CellStyle style = getBaseCellStyle(workbook);
        style.setFont(getFont(workbook, (short) 14, true));
        return style;
    }

    /**
     * 初始化--每列标题样式
     * @param workbook
     * @return
     */
    private CellStyle initTitleStyle(Workbook workbook) {
        CellStyle style = getBaseCellStyle(workbook);
        style.setFont(getFont(workbook, FONT_SIZE_TWELVE, true));
        //背景色
//        style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
        style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        return style;
    }

    /**
     * 初始化--数据行样式
     * @param workbook
     * @return
     */
    private CellStyle initStyles(Workbook workbook) {
        CellStyle style = getBaseCellStyle(workbook);
        style.setFont(getFont(workbook, FONT_SIZE_ELEVEN, false));
        style.setDataFormat(STRING_FORMAT);
        return style;
    }

    /**
     * 基础样式
     * @return
     */
    private CellStyle getBaseCellStyle(Workbook workbook) {
        CellStyle style = workbook.createCellStyle();
        //下边框
        style.setBorderBottom(BorderStyle.THIN);
        //左边框
        style.setBorderLeft(BorderStyle.THIN);
        //上边框
        style.setBorderTop(BorderStyle.THIN);
        //右边框
        style.setBorderRight(BorderStyle.THIN);
        //水平居中
        style.setAlignment(HorizontalAlignment.CENTER);
        //上下居中
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        //设置自动换行
        style.setWrapText(true);
        return style;
    }

    /**
     * 字体样式
     * @param size   字体大小
     * @param isBold 是否加粗
     * @return
     */
    private Font getFont(Workbook workbook, short size, boolean isBold) {
        Font font = workbook.createFont();
        //字体样式
        font.setFontName("宋体");
        //是否加粗
        font.setBold(isBold);
        //字体大小
        font.setFontHeightInPoints(size);
        return font;
    }
}

2、导出工具类 ExcelUtil

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

/**
 * @author fuHua
 * @date 2021年06月04日 14:09
 */
public class ExcelUtil {
    public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass, String fileName, ExcelType type, boolean isOneToMany, HttpServletResponse response){
        ExportParams exportParams = new ExportParams(title, sheetName,type);
        exportParams.setStyle(ExcelExportStylerUitl.class);
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams,pojoClass,list);
        if (workbook != null);
        //判断是否是一对多
        if (isOneToMany){
            setRowHeight(workbook);
        }
        downLoadExcel(fileName, response, workbook);
    }

    public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass, String fileName,  boolean setRowHeight, HttpServletResponse response){
        ExportParams exportParams = new ExportParams(title, sheetName);
        exportParams.setStyle(ExcelExportStylerUitl.class);
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams,pojoClass,list);
        if (workbook != null);
        //判断是否根据内容自适应行高
        if (setRowHeight){
            Sheet sheet = workbook.getSheetAt(0);
            for(int i = 0; i <= sheet.getLastRowNum(); i ++) {
                Row row = sheet.getRow(i);
                setRowHeight(row);
            }
        }
        downLoadExcel(fileName, response, workbook);
    }

    private static void downLoadExcel(String fileName, HttpServletResponse response, Workbook workbook) {
        try {
            response.setCharacterEncoding("UTF-8");
            response.setHeader("content-Type", "application/vnd.ms-excel");
            response.setHeader("Content-Disposition",
                    "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            workbook.write(response.getOutputStream());
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage());
        }
    }

    /**
     * 一对多,设置行高
     */
    private static void setRowHeight(Workbook workbook){
        Sheet sheet = workbook.getSheetAt(0);
        //设置第4列的列宽为60(下标从0开始),TestExportSub2Vo 不知道为什么设置了列宽但是不起作用,只能在这里单独设置
        sheet.setColumnWidth(3,60*256);
        for(int i = 0; i <= sheet.getLastRowNum(); i ++) {
            Row row = sheet.getRow(i);
            if (i==0){
                //设置第一行的行高(表格标题)
                row.setHeightInPoints(35);
            }else if (i == 1){
                //设置第二行的行高(表格表头)
                row.setHeightInPoints(25);
            }else {
            	//设置其他行的行高根据内容自适应
                setRowHeight(row);
            }
        }
    }

    private static void setRowHeight(Row row){
        //根据内容长度设置行高
        int enterCnt = 0;
        for(int j = 0; j < row.getPhysicalNumberOfCells(); j ++) {
            int rwsTemp = row.getCell(j).toString().length();
            //这里取每一行中的每一列字符长度最大的那一列的字符
            if (rwsTemp > enterCnt) {
                enterCnt = rwsTemp;
            }
        }
        //设置默认行高为35
        row.setHeightInPoints(35);
        //如果字符长度大于35,判断大了多少倍,根据倍数来设置相应的行高
        if (enterCnt>35){
            float d = enterCnt/35;
            float f = 35*d;
            /*if (d>2 && d<4){
                f = 35*2;
            }else if(d>=4 && d<6){
                f = 35*3;
            }else if (d>=6 && d<8){
                f = 35*4;
            }*/
            row.setHeightInPoints(f);
        }
    }
}

至于easyexcel要合并单元格的话,它没有像 easypoi 一样,有个属性可以控制合并,easyexcel需要自己写代码控制。然后根据内容自适应行高的话,easyexcel 应该也和这个差不多吧,还没研究过,下次有空去看看

以上是关于easypoi一对多,合并单元格,并且根据内容自适应行高的主要内容,如果未能解决你的问题,请参考以下文章

easypoi导出excel怎样设置相同内容不合并

怎么在WPS表格输入内容跳到其他的单元格?

poi读取复杂的Excel表格,如图

SpringBoot系列之集成EasyExcel导入合并行数据

SpringBoot系列之集成EasyExcel导入合并行数据

EXCEL如何根据A列相同内容在B列进行合并?