SpringBoot中使用EasyPoi导出excel_springboot easypoi导出excel_三婶儿的博客-程序员秘密

技术标签: SpringBoot中使用EasyPoi  EasyPoi  

以往数据的导入导出,都是使用传统的poi进行操作的。相对来说较为麻烦,推荐使用EasyPoi。几行代码,几个注解就可以完事,方便快捷。废话不多说,具体操作如下:

EasyPoi文档:https://easypoi.mydoc.io/#text_186900

一、在线快速创建一个SpringBoot项目

具体操作:https://blog.csdn.net/weixin_43770545/article/details/90764631

二、引入EasyPoi的pom依赖
      <!--EasyPoi导入导出-->
        <dependency>
            <groupId>cn.afterturn</groupId>
            <artifactId>easypoi-base</artifactId>
            <version>3.0.3</version>
        </dependency>
        <dependency>
            <groupId>cn.afterturn</groupId>
            <artifactId>easypoi-web</artifactId>
            <version>3.0.3</version> </dependency>
        <dependency>
            <groupId>cn.afterturn</groupId>
            <artifactId>easypoi-annotation</artifactId>
            <version>3.0.3</version>
        </dependency>

我在SpringBoot下使用的,所有依赖:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.1.5.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.wy</groupId>
	<artifactId>testEasyPoi</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>testEasyPoi</name>
	<description>Demo project for Spring Boot</description>

	<properties>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
        <!--EasyPoi导入导出-->
        <dependency>
            <groupId>cn.afterturn</groupId>
            <artifactId>easypoi-base</artifactId>
            <version>3.0.3</version>
        </dependency>
        <dependency>
            <groupId>cn.afterturn</groupId>
            <artifactId>easypoi-web</artifactId>
            <version>3.0.3</version> </dependency>
        <dependency>
            <groupId>cn.afterturn</groupId>
            <artifactId>easypoi-annotation</artifactId>
            <version>3.0.3</version>
        </dependency>
        <!-- 文件上传 -->
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.1</version>
        </dependency>
	</dependencies>
	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>
</project>
三、实体类上方加注解

我这边使用了lombok。getter setter和构造方法通过注解 @Data @AllArgsConstructor进行添加,不使用lombok也可手动添加。

要导出的数据可在实体类对应属性上方加@Excel()注解。可定义导出列的名称、宽度,以及性别可区分化(一般数据库中存储的性别为1和2),日期格式化等等。

package com.wy.testEasyPoi.entity;

import cn.afterturn.easypoi.excel.annotation.Excel;
import lombok.AllArgsConstructor;
import lombok.Data;

import java.util.Date;

/**
 * @author [email protected]
 * @version 1.0
 * @date 2019-08-30 15:55
 */
@Data
@AllArgsConstructor
public class Student {
    
    @Excel(name = "姓名", orderNum = "0", width = 30)
    private String name;
    @Excel(name = "性别", replace = {
    "男_1", "女_2"}, orderNum = "1", width = 30)
    private String sex;
    @Excel(name = "年龄", orderNum = "2", width = 10)
    private Integer age;
    @Excel(name = "生日", exportFormat = "yyyy-MM-dd", orderNum = "3", width = 30)
    private Date birthday;
}
四、工具类
package com.wy.testEasyPoi.util;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.web.multipart.MultipartFile;

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

/**
 * @author [email protected]
 * @version 1.0
 * @date 2019-08-30 15:51
 */
public class EasyPoiExcelUtil {
    

    public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass,
                                   String fileName, boolean isCreateHeader, HttpServletResponse response) {
    
        ExportParams exportParams = new ExportParams(title, sheetName);
        exportParams.setCreateHeadRows(isCreateHeader);
        defaultExport(list, pojoClass, fileName, response, exportParams);
    }

    public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass, String fileName,
                                   HttpServletResponse response) {
    
        defaultExport(list, pojoClass, fileName, response, new ExportParams(title, sheetName));
    }

    public static void exportExcel(List<Map<String, Object>> list, String fileName, HttpServletResponse response) {
    
        defaultExport(list, fileName, response);
    }

    private static void defaultExport(List<?> list, Class<?> pojoClass, String fileName,
                                      HttpServletResponse response, ExportParams exportParams) {
    
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, pojoClass, list);
        if (workbook != null) ;
        downLoadExcel(fileName, response, workbook);
    }

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

    private static void defaultExport(List<Map<String, Object>> list, String fileName, HttpServletResponse response) {
    
        Workbook workbook = ExcelExportUtil.exportExcel(list, ExcelType.HSSF);
        if (workbook != null) ;
        downLoadExcel(fileName, response, workbook);
    }

    public static <T> List<T> importExcel(String filePath, Integer titleRows, Integer headerRows, Class<T> pojoClass) {
    
        if (StringUtils.isBlank(filePath)) {
    
            return null;
        }
        ImportParams params = new ImportParams();
        params.setTitleRows(titleRows);
        params.setHeadRows(headerRows);
        List<T> list = null;
        try {
    
            list = ExcelImportUtil.importExcel(new File(filePath), pojoClass, params);
        } catch (NoSuchElementException e) {
    
            //throw new NormalException("模板不能为空");
        } catch (Exception e) {
    
            e.printStackTrace();
            //throw new NormalException(e.getMessage());
        }
        return list;
    }

    public static <T> List<T> importExcel(MultipartFile file, Integer titleRows, Integer headerRows, Class<T> pojoClass) {
    
        if (file == null) {
    
            return null;
        }
        ImportParams params = new ImportParams();
        params.setTitleRows(titleRows);
        params.setHeadRows(headerRows);
        List<T> list = null;
        try {
    
            list = ExcelImportUtil.importExcel(file.getInputStream(), pojoClass, params);
        } catch (NoSuchElementException e) {
    
            // throw new NormalException("excel文件不能为空");
        } catch (Exception e) {
    
            //throw new NormalException(e.getMessage());
            System.out.println(e.getMessage());
        }
        return list;
    }
}

本质上是调用的这个方法:

 private static void downLoadExcel(String fileName, HttpServletResponse response, Workbook workbook) {
    
        try {
    
            response.setHeader("content-Type", "application/vnd.ms-excel");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            response.setCharacterEncoding("UTF-8");
            workbook.write(response.getOutputStream());
        } catch (IOException e) {
    
            //throw new NormalException(e.getMessage());
        }
    }
五、Controller中定义
package com.wy.testEasyPoi.controller;

import com.wy.testEasyPoi.entity.Student;
import com.wy.testEasyPoi.util.EasyPoiExcelUtil;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * @author [email protected]
 * @version 1.0
 * @date 2019-08-30 16:07
 */
@RestController
public class TestEasyPoiExcelController {
    
    @GetMapping("/export")
    public void export(HttpServletResponse response){
    

        //模拟从数据库获取需要导出的数据,实战换为数据访问层返回的结果就行。
        List<Student> studentList = new ArrayList<>();
        Student student=new Student("山石","2",20,new java.util.Date());
        Student student1=new Student("张珍","2",20,new java.util.Date());
        Student student2=new Student("从","1",20,new java.util.Date());
        Student student3=new Student("家乐","1",20,new java.util.Date());
        Student student4=new Student("大潘","2",20,new java.util.Date());
        Student student5=new Student("婷婷","2",20,new java.util.Date());
        studentList.add(student);
        studentList.add(student1);
        studentList.add(student2);
        studentList.add(student3);
        studentList.add(student4);
        studentList.add(student5);
        //导出操作
        EasyPoiExcelUtil.exportExcel(studentList,"学生信息统计","学生信息",Student.class,"学生信息.xls",response);
    }
}
六、运行项目测试

项目启动后在浏览器中访问:http://localhost:8080/export
在这里插入图片描述
打开导出的excel
在这里插入图片描述

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/weixin_43770545/article/details/100191709

智能推荐

杰哥的IT之旅 | 2019年上半年文章汇总_Jack Tian的博客-程序员秘密

点击上方“杰哥的IT之旅”,选择“设为星标”干货、福利第一时间送达!作者 | JackTian来源 | 杰哥的IT之旅(ID:Jake_Internet)自运营公众号以来...

修改Android App名字_安卓修改app名称_六和七的博客-程序员秘密

打开AndroidManiFest.xml文件,在application下面会有一些APP配置相关的代码:修改android:label=“TEST”直接修改TEST的内容就可以更改APP名字如:android:label=“TEST1”...

【golang实战】使用golang发送以及接受数据_晴_空的博客-程序员秘密

发送以及接收 application/x-www-form-urlencoded 数据客户端发送数据,并设置 Content-Type 为 application/x-www-form-urlencodedfunc test() { var data = make(url.Values) data.Set("test2", "test-v") // 组装数据 c :=...

线性判别分析LDA降维只能降到“类别数-1”的原因_为什么lda降维降到n减1_Programming_miao的博客-程序员秘密

关键点在于类间散度矩阵Sb的秩最大为“类别数-1”,所以在计算特征向量矩阵(类内散度矩阵Sw的逆×类间散度矩阵Sb)时,可以发现只有“类别数-1”个特征值不为零的特征向量。这点和PCA是不同的。小Tip:被这个问题困扰了一天,以上是查阅资料+推导得出的结论,如果不对,欢迎指正哦~...

Linux下查找当前目录下文件大于指定大小的文件_查看当前目录大于某个文件_sasibingdu的博客-程序员秘密

find ./ -type f -size +5k #查找当前目录下大于等于5k的文件find ./ -type f -size -3M #查找当前目录下文件小于等于3M的文件

【我的ASP.NET学习笔记】学生成绩查询系统-数据库访问助手类sqlHelp--知识_chrxv66280的博客-程序员秘密

sqlHelp是一个基于.NET Framework的数据库操作组件,组件中包含数据库操作方法。无需重复的去写SqlConnection,SqlCommand,SqlDataReader等。SqlHelp封装过后只需要给方法传入一些参数如数据库连接字符串,SQL参数等,就可以访问数据库了...

随便推点

django 获取 axios get 过来的数据_Django实战017:django+vue+redis项目_weixin_39747568的博客-程序员秘密

最近写了一个小项目,用django+vue+redis实现的echarts图表。主要功能是利用redis丰富的数据类型和超高读写性能来存储数据,这样可以快速响应用户需求并支撑海量的数据和流量。左边提供了一个数据输入框(可以收起),右边提供了2个不同形式的图表来展示redis中的数据。页面载入时自动显示reids中的数据,左边参数提交数据之后立马刷新右边的图表。Vue前端实现前端主要通过Vue脚手架...

有了这 4 款工具,老板再也不怕我写烂SQL了_sql不规范操作如何写工具_fengzongfu的博客-程序员秘密

对于正在运行的mysql 性能如何?参数设置的是否合理?账号设置的是否存在安全隐患?你是否了然于胸?俗话说工欲善其事,必先利其器,定期对你的MYSQL数据库进行一个体检,是保证数据库安全运行的重要手段。今天和大家分享几个mysql 优化的工具,你可以使用它们对你的mysql进行一个体检,生成awr报告,让你从整体上把握你的数据库的性能情况。1、mysqltuner.pl这是...

DDD领域驱动篇——第一章(一文带你领略DDD、微服务和中台设计)_ddd领域驱动(一)_风清扬逍遥子的博客-程序员秘密

DDD到底是什么概念,和微服务和中台之间又有什么样的联系,带你走进DDD!!

NKPC7-2155-Crazy Review_weixin_33910434的博客-程序员秘密

1. 概述    题目出的很有意思,在有限的时间内,合理分配时间,得到最大的分数。标注答案是动态规划。感觉和编程之美上,一个求最大连续子数组之和的题目很像,因为两道题都涉及到了两个动态规划,而且其中的一个动态规划使用另一个动态规划。2. 方法    首先,判断所有课程上限是否到60分,    然后,对于没有到60分的课程分别先学习到60分,并且更新S,V和H。    接着,计算使用剩下...

2017年美团Java程序员开发,看我如何拿到offer_huangshulang1234的博客-程序员秘密

2017年美团Java程序员开发,看我如何拿到offer热乎的面经,昨天面的美团,虽然面完了HR面,但是感觉希望不大,希望能走运拿到offer吧。三面技术面面经如下:一面:中间省略掉大概几个问题,因为我不记得了,下面记得的基本都是我没怎么答好的。。。1.了解SOA,微服务吗?2.分布式系统如何负载均衡?如何确定访问的资源在哪个服务器上?一.轮询。二.随机。三.最小响

hive-查询速度快-orc表-建立格式_weixin_45762425的博客-程序员秘密

create external table if not exists orders_orc(id int,goods_id int,goods_type int,goods_number int,order_number string,account_id int,from int,deleted boolean,status int,payment int,pay_tim...

推荐文章

热门文章

相关标签