easypoi以最简单的方式实现多级表头导入导出

导出效果图:
在这里插入图片描述

数据导入效果图:
在这里插入图片描述

存入mysql库效果图:
在这里插入图片描述
效果也看到了,基本能满足所需要求,这种复杂的表头都是自定义的,根据模板直接使用,特别容易上手。

1,导入所需依赖
 		<!--导入导出-->
        <dependency>
            <groupId>cn.afterturn</groupId>
            <artifactId>easypoi-base</artifactId>
            <version>4.2.0</version>
        </dependency>
2,给数据库实体类添加@Excel注解

这是我测试创建的一个easypoi_test表,字段简单(无需特别关注)
在这里插入图片描述
实体类与数据库的表对应,这没什么好说的

EsaypoiTest .java

package com.myqxin.pojo;

import cn.afterturn.easypoi.excel.annotation.Excel;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import lombok.EqualsAndHashCode;

import java.io.Serializable;

/**
 * <p>
 * 
 * </p>
 *
 * @author myqxin
 * @since 2021-11-05
 */
@Data
@EqualsAndHashCode(callSuper = false)
@TableName("esaypoi_test")
public class EsaypoiTest implements Serializable {

    private static final long serialVersionUID = 1L;

    @TableId(value = "id", type = IdType.AUTO)
    private Integer id;
    @Excel(name = "名称1",groupName = "基本信息")
    private String m1;
    @Excel(name = "名称2",groupName = "名称15",replace = {"男_1","女_0"})
    private String m2;
    @Excel(name = "名称3")
    private String m3;
    @Excel(name = "名称4",groupName = "名称16")
    private String m4;
    @Excel(name = "名称5")
    private String m5;
    @Excel(name = "名称6")
    private String m6;
    @Excel(name = "名称7")
    private String m7;
    @Excel(name = "名称8")
    private String m8;
    @Excel(name = "名称9",groupName = "特殊信息")
    private String m9;
    @Excel(name = "名称10",groupName = "名称17")
    private String m10;
    @Excel(name = "名称11")
    private String m11;
    @Excel(name = "名称12",groupName = "名称18")
    private String m12;
    @Excel(name = "名称13")
    private String m13;
    @Excel(name = "名称14")
    private String m14;

}

关于@Excel注解的详细说明,看官网:http://easypoi.mydoc.io

我这里对它做简单的解释:

属性描述
name与离表格数据最近的哪一行表头的名称
groupName一个组合,在第一个表头位置加上这个,下一个不用加,默认到结尾
replace文本替换

@Excel(name=“”):可以理解对应这个红框里面的值,离数据最近的一行表头

在这里插入图片描述
@Excel(groupName=“”):用来区分当前单元格所属那个表格范围

我这里用了三种颜色来标示,我说的应该能明白吧,那个groupName会从当前单元格开始,一直包容这之后的单元格,但他不会对同级的进行包容,例如m8(名称8)就是和“基本信息”处在同级。基本信息包含了m1~m7(名称1-名称7)。名称15就只包含了m2,m3(名称2,名称3)。名称16就包含了m4,m5,m6(名称4,名称5,名称6)

在这里插入图片描述
在这里插入图片描述
@Excel(replace = {“”}):用于文本替换的

在这里插入图片描述

在这里插入图片描述
在这里插入图片描述
导入的时候就会自动给我替换成想要的值了

3,execl数据导入,案例:
    @PostMapping("/import")
    public void importData(MultipartFile file) throws Exception {
        ImportParams params = new ImportParams();
        params.setTitleRows(1);
        // 从第几行开始,因为第一个大标题被上面的参数给占了,所以不是4
        params.setHeadRows(3);
        List<EsaypoiTest> list = ExcelImportUtil.importExcel(file.getInputStream(), EsaypoiTest.class, params);
        list.forEach(System.out::println);
        for (EsaypoiTest esaypoiTest : list) {
            esaypoiTestService.save(esaypoiTest);
        }
    }

导入相对简单,数据入库效果:

在这里插入图片描述

4,数据库数据导出到excel表
  • 设置导出格式模板

在这里插入图片描述

在自定义的模板下,设置成这样的形式,可以了,表头与导入时保持一致。只是导出的时候,导出的模板没有数据,只有属性值,用来接收数据的

代码实现:

    @GetMapping("/export")
    public void exportData(HttpServletResponse response) throws Exception {
        List<EsaypoiTest> list = esaypoiTestService.list();
        // 模板路径
        String path = "C:\\Users\\myqxin\\Desktop\\poi\\模板测试.xlsx";
        TemplateExportParams temp = new TemplateExportParams(path);
        HashMap<String, Object> map = new HashMap<>();
        map.put("maplist", list);
        Workbook workbook = ExcelExportUtil.exportExcel(temp, map);
        if (workbook == null) {
            //读取模板失败
        }
        // 设置excel的文件名称
        String fileName = "模板测试成功" + ".xlsx";

        // 重置响应对象
        response.reset();
        try {
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        response.setContentType("textml;charset=utf-8");
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        // 写出数据输出流到页面
        try {
            OutputStream output = response.getOutputStream();
            BufferedOutputStream bufferedOutPut = new BufferedOutputStream(output);
            workbook.write(bufferedOutPut);
            bufferedOutPut.flush();
            bufferedOutPut.close();
            output.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

在这里插入图片描述
在这里插入图片描述
注意事项:在遍历的列中不能有空单元格

在这里插入图片描述
如非要留着占用,可以使用&NULL&进行占位
在这里插入图片描述

更多问题参考这里:https://blog.csdn.net/weixin_38312502/article/details/105627498

  • 13
    点赞
  • 82
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 13
    评论
### 回答1: easypoi是一款Java的Excel导入导出工具,支持多级表头导出。在使用easypoi导出Excel时,可以通过设置表头的行数和列数来实现多级表头导出。具体实现方法可以参考easypoi的官方文档或者相关的教程。需要注意的是,在设置多级表头时,需要根据实际情况设置每个单元格的合并行数和列数,以确保表头的显示效果正确。 ### 回答2: Easypoi是一个Java的Excel处理框架,它可以方便快捷地导入导出Excel文档。在使用Easypoi进行Excel导出时,实现多级表头的方法是非常简单的。 首先,需要在Java类中定义表头的结构。在Easypoi中,可以使用实体类的注解来定义表头,例如 @Excel(name = "学生信息", width = 20) 代表一个表头的名称为“学生信息”,宽度为20个字符。对于多级表头的情况,可以在实体类中嵌套另一个实体类来表示多级表头的结构。 接着,使用excel导出工具类进行导出。在使用Easypoi进行Excel导出时,可以使用ExcelExportUtil.exportExcel方法来实现。该方法需要传入一个Excel导出参数的包装类,其中包括Excel文档的标题、表头、表数据等信息。 对于多级表头的情况,可以通过设置ExcelExportParams的headMap参数来实现。该参数是一个Map<String, Integer>对象,其中key为表头的文本,value为该表头所占据的列数。例如,要实现一个两层表头,第一层表头为“学生信息”,占据4列;第二层表头为“基本信息”和“成绩信息”,分别占据2列,则可以定义headMap参数为: Map<String, Integer> headMap = new LinkedHashMap<>(); headMap.put("学生信息", 4); headMap.put("基本信息", 2); headMap.put("成绩信息", 2); 最后,调用ExcelExportUtil.exportExcel方法进行导出即可。完整的导出代码如下: ```java List<Student> students = new ArrayList<>(); // TODO: 设置学生列表数据 // 定义 Excel 导出参数 ExcelExportParams exportParams = new ExcelExportParams(); exportParams.setTitle("学生信息表"); exportParams.setHead(StudentExcelExportModel.class, headMap); // 导出 Excel Workbook workbook = ExcelExportUtil.exportExcel(exportParams, StudentExcelExportModel.class, students); workbook.write(outputStream); ``` 需要注意的是,ExcelExportParams的setHead方法需要传入一个Class类型的参数,用于指定表头的字段。这个Class可以和数据实体类不一致,因为其只关心表头信息。 综上所述,使用Easypoi导出Excel多级表头非常方便。只需在数据实体类中定义表头结构,然后设置Excel导出参数的headMap参数并调用ExcelExportUtil.exportExcel方法即可。 ### 回答3: Easypoi是一个开源的Java工具库,用于生成Excel、Word和Pdf等文档格式,它提供了简单易用的API,可以帮助我们快速导出Excel数据。在使用Easypoi导出Excel时,往往遇到多级表头的情况,本文将详细介绍Easypoi导出Excel多级表头实现方法。 Easypoi支持导出Excel的表头分为两种:固定表头和动态表头。因为不同类型的表头实现方式不同,所以我们需要分开讲解。 1. 固定表头导出 固定表头就是表头中包含多个级别,其中每个级别都是已经确定的,不会随数据量的增加而增加。在Easypoi中,我们可以使用@TableStyle注解中的headRows和secondHeadRows来设置多级表头的行数,具体实现步骤如下: ① 在需要导出的实体类中定义表头,例如: public class Student { @Excel(name = "学号", orderNum = "0", width = 15) private String id; @Excel(name = "姓名", orderNum = "1", width = 15) private String name; @Excel(name = "语文", orderNum = "2", width = 15) private Integer chinese; @Excel(name = "数学", orderNum = "3", width = 15) private Integer math; @Excel(name = "英语", orderNum = "4", width = 15) private Integer english; } ② 在需要导出的Controller中设置表格样式,使用@TableStyle注解,例如: @GetMapping("/exportStudent") public void exportStudent(HttpServletResponse response) throws IOException { // 模拟数据 List<Student> studentList = new ArrayList<>(); Student stu1 = new Student("001", "张三", 80, 88, 90); Student stu2 = new Student("002", "李四", 85, 90, 87); studentList.add(stu1); studentList.add(stu2); // 设置表格样式 TableStyle style = new TableStyle(); style.setTableHeadFont(getFontHeight((short) 12, "黑体")); style.setTableContentBackGroundColor(IndexedColors.WHITE); style.setTableHeadBackGroundColor(IndexedColors.PINK1); style.setTableTitleBackGroundColor(IndexedColors.GOLD); style.setTableTitleFont(getFontHeight((short) 16, "楷体_GB2312")); style.setTableHeadSecondBackGroundColor(IndexedColors.LIGHT_YELLOW); style.setTableHeadThreeBackGroundColor(IndexedColors.LIGHT_ORANGE); // 表头分两行,第一行3列,第二行2列 style.setHeadRows(1); style.setSecondHeadRows(1); // 导出Excel文件 ExportParams params = new ExportParams("学生信息表", "学生信息", ExcelType.XSSF); params.setStyle(style); Workbook workbook = ExcelExportUtil.exportExcel(params, Student.class, studentList); response.setContentType("application/vnd.ms-excel"); response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(params.getExcelName(), "UTF-8")); response.flushBuffer(); workbook.write(response.getOutputStream()); } ③ 运行程序即可看到导出的Excel文件中含有多级表头。 2. 动态表头导出 动态表头就是表头中包含多个级别,其中每个级别的列数是不固定的,会根据实际数据动态增加。在Easypoi中,我们可以通过定义NestedColumn注解的方式动态设置表头名称和列数,具体实现步骤如下: ① 在需要导出的实体类中定义表头,例如: public class Student { @Excel(name = "学号", orderNum = "0", width = 15) private String id; @Excel(name = "姓名", orderNum = "1", width = 15) private String name; @Excel(name = "成绩", orderNum = "2", width = 15) @NestedColumn(nestedColumns = {@Excel(name = "语文", orderNum = "1", width = 15), @Excel(name = "数学", orderNum = "2", width = 15), @Excel(name = "英语", orderNum = "3", width = 15)}) private List<Double> scores; } ② 在需要导出的Controller中设置表格样式,例如: @GetMapping("/exportStudent") public void exportStudent(HttpServletResponse response) throws IOException { // 模拟数据 List<Student> studentList = new ArrayList<>(); Student stu1 = new Student("001", "张三", Arrays.asList(80.0, 88.0, 90.0)); Student stu2 = new Student("002", "李四", Arrays.asList(85.0, 90.0, 87.0)); studentList.add(stu1); studentList.add(stu2); // 设置表格样式 TableStyle style = new TableStyle(); style.setTableHeadFont(getFontHeight((short) 12, "黑体")); style.setTableContentBackGroundColor(IndexedColors.WHITE); style.setTableHeadBackGroundColor(IndexedColors.PINK1); style.setTableTitleBackGroundColor(IndexedColors.GOLD); style.setTableTitleFont(getFontHeight((short) 16, "楷体_GB2312")); style.setTableHeadSecondBackGroundColor(IndexedColors.LIGHT_YELLOW); style.setTableHeadThreeBackGroundColor(IndexedColors.LIGHT_ORANGE); // 导出Excel文件 ExportParams params = new ExportParams("学生信息表", "学生信息", ExcelType.XSSF); params.setStyle(style); Workbook workbook = ExcelExportUtil.exportExcel(params, Student.class, studentList); response.setContentType("application/vnd.ms-excel"); response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(params.getExcelName(), "UTF-8")); response.flushBuffer(); workbook.write(response.getOutputStream()); } ③ 运行程序即可看到动态表头导出结果。 以上就是Easypoi导出Excel多级表头实现方法。对于不同类型的表头,我们可以根据需要选择对应的方式实现,使得表格样式更加美观、易于理解。
评论 13
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

子非我鱼

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值