EasyPOI工具可以方便的写出Excel导出,Excel模板导出,Excel导入,Word模板导出,通过简单的注解和模板

导入maven依赖

<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>
<!-- Swagger2 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.7.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.7.0</version>
</dependency>
<!-- slf4j -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.25</version>
</dependency>
<!-- easypoi导入导出excel -->
<!-- easypoi-base 导入导出的工具包,可以完成Excel导出,导入,Word的导出,Excel的导出功能 -->
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-base</artifactId>
<version>3.1.0</version>
</dependency>
<!-- easypoi-web 耦合了spring-mvc 基于AbstractView,极大的简化spring-mvc下的导出功能 -->
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-web</artifactId>
<version>3.1.0</version>
</dependency>
<!-- easypoi-annotation 基础注解包,作用与实体对象上,拆分后方便maven多工程的依赖管理 -->
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-annotation</artifactId>
<version>3.1.0</version>
</dependency>

创建实体类:课程-老师-学生

package com.qjc.excel.entity;

import cn.afterturn.easypoi.excel.annotation.Excel;
import cn.afterturn.easypoi.excel.annotation.ExcelCollection;
import cn.afterturn.easypoi.excel.annotation.ExcelEntity;
import cn.afterturn.easypoi.excel.annotation.ExcelTarget;
import lombok.Data; import java.util.List; /**
* @Description:
* @Author: qjc
* @Date: 2019/11/27
*/
@Data
@ExcelTarget("courseEntity")
public class CourseEntity {
/**
* @Excel 作用到filed上面, 是对Excel一列的一个描述
* @ExcelCollection 表示一个集合, 主要针对一对多的导出, 比如一个老师对应多个科目, 科目就可以用集合表示
* @ExcelEntity 表示一个继续深入导出的实体, 但他没有太多的实际意义, 只是告诉系统这个对象里面同样有导出的字段
* @ExcelIgnore 和名字一样表示这个字段被忽略跳过这个导导出
* @ExcelTarget 这个是作用于最外层的对象, 描述这个对象的id, 以便支持一个对象可以针对不同导出做出不同处理
*/ private String id;
/**
* 课程名称
*/
@Excel(name = "课程名称", orderNum = "1", width = 25)
private String name;
/**
* 老师主键
*/
@ExcelEntity(id = "absent")
private TeacherEntity mathTeacher; @ExcelCollection(name = "学生", orderNum = "4")
private List<StudentEntity> students;
}
package com.qjc.excel.entity;

import cn.afterturn.easypoi.excel.annotation.Excel;
import cn.afterturn.easypoi.excel.annotation.ExcelTarget;
import lombok.Data; /**
* @Description:
* @Author: qjc
* @Date: 2019/11/27
*/
@ExcelTarget("teacherEntity")
@Data
public class TeacherEntity { private String id;
/**
* name
*/
@Excel(name = "主讲老师_major,代课老师_absent", orderNum = "1", isImportField = "true_major,true_absent")
private String name;
}
package com.qjc.excel.entity;

import cn.afterturn.easypoi.excel.annotation.Excel;
import lombok.Data;
import lombok.ToString; import java.util.Date; /**
* @Description:
* @Author: qjc
* @Date: 2019/11/27
*/
@Data
@ToString
public class StudentEntity { /**
* id
*/
private String id;
/**
* 学生姓名
*/
@Excel(name = "学生姓名", height = 20, width = 30, isImportField = "true_st")
private String name;
/**
* 学生性别
*/
@Excel(name = "学生性别", replace = {"男_1", "女_2"}, suffix = "生", isImportField = "true_st")
private int sex; @Excel(name = "出生日期", databaseFormat = "yyyyMMddHHmmss", format = "yyyy-MM-dd", isImportField = "true_st", width = 20)
private Date birthday; @Excel(name = "进校日期", databaseFormat = "yyyyMMddHHmmss", format = "yyyy-MM-dd")
private Date registrationDate;
}

导入导出工具类

package com.qjc.excel.utils;

import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException; import javax.servlet.http.HttpServletResponse; import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.web.multipart.MultipartFile; 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; /**
* @Description:
* @Author: qjc
* @Date: 2019/11/27
*/
public class ExcelUtil { /**
* 导出数据到Excel
*
* @param list 数据集合
* @param title 数据第一行标题
* @param sheetName Sheet名称
* @param pojoClass 实体Class
* @param fileName 文件名
* @param isCreateHeader 是否创建数据表头
* @param response 响应
*/
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); } /**
* 导出数据到Excel
*
* @param list 数据集合
* @param title 数据第一行标题
* @param sheetName Sheet名称
* @param pojoClass 实体Class
* @param fileName 文件名
* @param response 响应
*/
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)
throws Exception {
defaultExport(list, fileName, response);
} private static void defaultExport(List<?> list, Class<?> pojoClass, String fileName, HttpServletResponse response,
ExportParams exportParams) {
Workbook workbook = null;
try {
workbook = ExcelExportUtil.exportExcel(exportParams, pojoClass, list);
} catch (Exception e) {
e.printStackTrace();
}
if (workbook != null)
try {
downLoadExcel(fileName, response, workbook);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} private static void downLoadExcel(String fileName, HttpServletResponse response, Workbook workbook)
throws Exception {
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 Exception(e.getMessage());
}
} private static void defaultExport(List<Map<String, Object>> list, String fileName, HttpServletResponse response)
throws Exception {
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)
throws Exception {
if (org.apache.commons.lang3.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 Exception("模板不能为空");
} catch (Exception e) {
e.printStackTrace();
throw new Exception(e.getMessage());
}
return list;
} /**
* 导入(解析)Excel
*
* @param file Excel文件
* @param titleRows 标题行数
* @param headerRows 表头行数
* @param pojoClass 实体类
* @param <T>
* @return
* @throws Exception
*/
public static <T> List<T> importExcel(MultipartFile file, Integer titleRows, Integer headerRows, Class<T> pojoClass)
throws Exception {
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 Exception("excel文件不能为空");
} catch (Exception e) {
throw new Exception(e.getMessage());
}
return list;
} }

Controller

package com.qjc.excel.controller;

import java.util.ArrayList;
import java.util.List; import javax.servlet.http.HttpServletResponse; import com.qjc.excel.entity.CourseEntity;
import com.qjc.excel.entity.StudentEntity;
import com.qjc.excel.entity.TeacherEntity;
import com.qjc.excel.utils.DateUtils;
import com.qjc.excel.utils.ExcelUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile; /**
* @Description:
* @Author: qjc
* @Date: 2019/11/27
*/
@Api(value = "EasyPOI接口", tags = {"EasyPOI接口"})
@RestController
@CrossOrigin(origins = "*", methods = {RequestMethod.GET, RequestMethod.POST, RequestMethod.DELETE, RequestMethod.PUT})
@Slf4j
public class FileController { @ApiOperation(value = "对象定义--导出数据到Excel", notes = "对象定义--导出数据到Excel")
@RequestMapping(value = "/exportExcel/object", method = RequestMethod.GET)
public void exportData(HttpServletResponse response) {
//从数据库中查询数据,直接用浏览器访问http://localhost:8777/exportExcel/object即可
List<StudentEntity> studentEntityList = createStudents(); //导出操作
ExcelUtil.exportExcel(studentEntityList, "四大学生", "EasyPOISheet", StudentEntity.class, "学生.xls", response);
} @ApiOperation(value = "导入Excel", notes = "导入Excel")
@RequestMapping(value = "/importExcel", method = RequestMethod.POST)
public void importExcel(@RequestParam("textFile") MultipartFile file) throws Exception {
//解析excel,直接通过swagger上传Excel就行
List<StudentEntity> studentEntityList = ExcelUtil.importExcel(file, 1, 1, StudentEntity.class);
for (StudentEntity studentEntity : studentEntityList) {
System.err.println(studentEntity.toString());
}
} @ApiOperation(value = "集合定义--导出数据到Excel", notes = "集合定义--导出数据到Excel")
@RequestMapping(value = "/importExcel/collection", method = RequestMethod.GET)
public void importCollectionExcel(HttpServletResponse response) {
//浏览器直接访问http://localhost:8777/importExcel/collection
List<CourseEntity> courseEntityList = new ArrayList<>(); CourseEntity courseEntity1 = new CourseEntity();
courseEntity1.setName("生物");
TeacherEntity teacherEntity1 = new TeacherEntity();
teacherEntity1.setName("刘备");
courseEntity1.setMathTeacher(teacherEntity1);
courseEntity1.setStudents(createStudents()); courseEntityList.add(courseEntity1); CourseEntity courseEntity2 = new CourseEntity();
courseEntity2.setName("化学");
TeacherEntity teacherEntity2 = new TeacherEntity();
teacherEntity2.setName("曹操");
courseEntity2.setMathTeacher(teacherEntity2);
courseEntity2.setStudents(createStudents()); courseEntityList.add(courseEntity2); //导出操作
ExcelUtil.exportExcel(courseEntityList, "课程-老师-学生", "course", CourseEntity.class, "课程.xls", response);
} /**
* 创建学生集合
*
* @return
*/
private List<StudentEntity> createStudents() {
List<StudentEntity> studentEntityList = new ArrayList<>();
StudentEntity studentEntity1 = new StudentEntity();
studentEntity1.setName("刘德华");
studentEntity1.setSex(1);
studentEntity1.setBirthday(DateUtils.formatStringToDate("2010-01-01", "yyyy-MM-dd"));
studentEntity1.setRegistrationDate(DateUtils.formatStringToDate("2015-01-01", "yyyy-MM-dd"));
StudentEntity studentEntity2 = new StudentEntity();
studentEntity2.setName("黎明");
studentEntity2.setSex(1);
studentEntity2.setBirthday(DateUtils.formatStringToDate("2009-01-01", "yyyy-MM-dd"));
studentEntity2.setRegistrationDate(DateUtils.formatStringToDate("2014-01-01", "yyyy-MM-dd"));
StudentEntity studentEntity3 = new StudentEntity();
studentEntity3.setName("郭富城");
studentEntity3.setSex(2);
studentEntity3.setBirthday(DateUtils.formatStringToDate("2008-01-01", "yyyy-MM-dd"));
studentEntity3.setRegistrationDate(DateUtils.formatStringToDate("2013-01-01", "yyyy-MM-dd"));
StudentEntity studentEntity4 = new StudentEntity();
studentEntity4.setName("张学友");
studentEntity4.setSex(2);
studentEntity4.setBirthday(DateUtils.formatStringToDate("2011-01-01", "yyyy-MM-dd"));
studentEntity4.setRegistrationDate(DateUtils.formatStringToDate("2016-01-01", "yyyy-MM-dd")); studentEntityList.add(studentEntity1);
studentEntityList.add(studentEntity2);
studentEntityList.add(studentEntity3);
studentEntityList.add(studentEntity4);
return studentEntityList;
} }

源码链接:

https://gitee.com/xiaorenwu_dashije/easypoi_example.git

EasyPOI导入导出Excel的更多相关文章

  1. EasyPoi 导入导出Excel时使用GroupName的踩坑解决过程

    一.开发功能介绍: 简单的一个excel导入功能 二.Excel导入模板(大致模板没写全): 姓名 性别 生日 客户分类 联系人姓名 联系人部门 备注 材料 综合 采购 张三 男 1994/05/25 ...

  2. ASP.NET Core 导入导出Excel xlsx 文件

    ASP.NET Core 使用EPPlus.Core导入导出Excel xlsx 文件,EPPlus.Core支持Excel 2007/2010 xlsx文件导入导出,可以运行在Windows, Li ...

  3. thinkphp导入导出excel表单数据

    在PHP项目经常要导入导出Excel表单. 先去下载PHPExcel类库文件,放到相应位置. 我在thinkphp框架中的位置为ThinkPHP/Library/Org/Util/ 导入 在页面上传e ...

  4. 导入导出Excel工具类ExcelUtil

    前言 前段时间做的分布式集成平台项目中,许多模块都用到了导入导出Excel的功能,于是决定封装一个ExcelUtil类,专门用来处理Excel的导入和导出 本项目的持久化层用的是JPA(底层用hibe ...

  5. php中导入导出excel的原理

    在php中我们要经常导入导出excel文件,方便后台管理.那么php导入和导出excel的原理到底是什么呢?excel分为两大版本excel2007(后缀.xlsx).excel2003(后缀.xls ...

  6. NPOI导入导出EXCEL通用类,供参考,可直接使用在WinForm项目中

    以下是NPOI导入导出EXCEL通用类,是在别人的代码上进行优化的,兼容xls与xlsx文件格式,供参考,可直接使用在WinForm项目中,由于XSSFWorkbook类型的Write方法限制,Wri ...

  7. .NET导入导出Excel

    若是开发后台系统,ASP.NET MVC中总是涉及了很多导入导出Excel的问题,有的时候处理起来比较烦 如果能使用以下代码解决,就完美了 public class ReportModel { [Ex ...

  8. Java利用POI导入导出Excel中的数据

         首先谈一下今天发生的一件开心的事,本着一颗android的心我被分配到了PB组,身在曹营心在汉啊!好吧,今天要记录和分享的是Java利用POI导入导出Excel中的数据.下面POI包的下载地 ...

  9. .Net MVC 导入导出Excel总结(三种导出Excel方法,一种导入Excel方法) 通过MVC控制器导出导入Excel文件(可用于java SSH架构)

    .Net MVC  导入导出Excel总结(三种导出Excel方法,一种导入Excel方法) [原文地址] 通过MVC控制器导出导入Excel文件(可用于java SSH架构)   public cl ...

随机推荐

  1. 从ASP.NET到ASP.NET Core差异变化

    MSDN原文:链接 ASP.NET Core项目为开发人员提供了针对.NET Core,.NET Framework2种实现方式,根据官网通告NETCORE3.0后将取消对.NET Framework ...

  2. eggjs异常捕获机制

    1. try catch捕获异步链中的方法 2. ctx.runInBackground(scope)捕获跳出异步链的方法 // 旧代码 class HomeController extends Co ...

  3. Android闪屏问题的分析思路

    http://www.devba.com/index.php/archives/6157.html  Android闪屏问题的分析思路 作者:孤风一剑   发布:2015-01-22 12:35   ...

  4. 使用java计算数组方差和标准差

    使用java计算数组方差和标准差 觉得有用的话,欢迎一起讨论相互学习~Follow Me 首先给出方差和标准差的计算公式 代码 public class Cal_sta { double Sum(do ...

  5. org.apache.hadoop.fs.FsUrlStreamHandlerFactory 在哪个jar包

    org.apache.hadoop.fs.FsUrlStreamHandlerFactory在org.apache.hadoop类中,org.apache.hadoop在hadoop安装目录下.

  6. Springboot中IDE支持两种打包方式,即jar包和war包

    Springboot中IDE支持两种打包方式,即jar包和war包 打包之前修改pom.xml中的packaging节点,改为jar或者war    在项目的根目录执行maven 命令clean pa ...

  7. [转]Nodejs利用phantom 将html生成图片

    原文地址:https://www.jianshu.com/p/8679f469e8d6 不过下载起来比较麻烦. 需要手动下载,然后将其添加到PATH中. 下载链接: https://sl-m-ssl. ...

  8. spring boot的actuator

    actuator官方的介绍 Spring Boot includes a number of additional features to help you monitor and manage yo ...

  9. Referenced file contains errors (http://www.springframework.org/...解决

    今天打开老项目出现如下错误: Referenced file contains errors (http://www.springframework.org/schema/context/spring ...

  10. OpenLayers加载高德地图离线瓦片地图

    本文使用OpenLayers最新版本V5.3.0演示:如何使用OpenLayer加载谷歌地球离线瓦片地图.OpenLayers 5.3.0下载地址为:https://github.com/openla ...