EasyPOI导入导出Excel
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的更多相关文章
- EasyPoi 导入导出Excel时使用GroupName的踩坑解决过程
一.开发功能介绍: 简单的一个excel导入功能 二.Excel导入模板(大致模板没写全): 姓名 性别 生日 客户分类 联系人姓名 联系人部门 备注 材料 综合 采购 张三 男 1994/05/25 ...
- ASP.NET Core 导入导出Excel xlsx 文件
ASP.NET Core 使用EPPlus.Core导入导出Excel xlsx 文件,EPPlus.Core支持Excel 2007/2010 xlsx文件导入导出,可以运行在Windows, Li ...
- thinkphp导入导出excel表单数据
在PHP项目经常要导入导出Excel表单. 先去下载PHPExcel类库文件,放到相应位置. 我在thinkphp框架中的位置为ThinkPHP/Library/Org/Util/ 导入 在页面上传e ...
- 导入导出Excel工具类ExcelUtil
前言 前段时间做的分布式集成平台项目中,许多模块都用到了导入导出Excel的功能,于是决定封装一个ExcelUtil类,专门用来处理Excel的导入和导出 本项目的持久化层用的是JPA(底层用hibe ...
- php中导入导出excel的原理
在php中我们要经常导入导出excel文件,方便后台管理.那么php导入和导出excel的原理到底是什么呢?excel分为两大版本excel2007(后缀.xlsx).excel2003(后缀.xls ...
- NPOI导入导出EXCEL通用类,供参考,可直接使用在WinForm项目中
以下是NPOI导入导出EXCEL通用类,是在别人的代码上进行优化的,兼容xls与xlsx文件格式,供参考,可直接使用在WinForm项目中,由于XSSFWorkbook类型的Write方法限制,Wri ...
- .NET导入导出Excel
若是开发后台系统,ASP.NET MVC中总是涉及了很多导入导出Excel的问题,有的时候处理起来比较烦 如果能使用以下代码解决,就完美了 public class ReportModel { [Ex ...
- Java利用POI导入导出Excel中的数据
首先谈一下今天发生的一件开心的事,本着一颗android的心我被分配到了PB组,身在曹营心在汉啊!好吧,今天要记录和分享的是Java利用POI导入导出Excel中的数据.下面POI包的下载地 ...
- .Net MVC 导入导出Excel总结(三种导出Excel方法,一种导入Excel方法) 通过MVC控制器导出导入Excel文件(可用于java SSH架构)
.Net MVC 导入导出Excel总结(三种导出Excel方法,一种导入Excel方法) [原文地址] 通过MVC控制器导出导入Excel文件(可用于java SSH架构) public cl ...
随机推荐
- odoo开发笔记 -- 触发机制/埋点设置
场景描述: 项目需求中,经常会需要,当某个字段处某个特定状态时候,触发执行特定的方法:或者创建某条记录的时候,同时做另一个操作:如何实现类似的需求? 实现方式: odoo中提供了几种触发方式: 1. ...
- 《绯雨骑士团》Demo,框架实现,寻路打怪
在家无事花几天做了个放置挂机demo,做着玩吧.和海拓的<凡人修仙传>类似吧,自动挂机刷怪打boss数值游戏,但是我比较喜欢二次元的,所以选了<绯雨骑士团>的资源. 参考了以下 ...
- python 使用sqlalchemy进行数据库操作
sqlalchemy是python下一个著名的数据库orm库,可以方便地进行数据表创建.数据增删改查等操作 最详细的教程,见官方:https://docs.sqlalchemy.org 这里列举一些常 ...
- Hive学习笔记——metadata
Hive结构体系 https://blog.csdn.net/zhoudaxia/article/details/8855937 可以在hive的jdbc接口中使用getMetaData方法来获取hi ...
- phpspreadsheet 中文文档(二) 结构+自动筛选
2019年10月11日13:55:41 原理图 自动加载器 PhpSpreadsheet依赖于Composer自动加载器.因此,在独立使用PhpSpreadsheet之前,请确保先运行composer ...
- kubernetes之kubelet运行机制分析
kubernetes集群中,每个Node节点工作节点上都会启动一个kubelet服务进程.用于处理master节点下发到本节点的任务,管理pod和pod中的容器.每个kubelet进程都会在API S ...
- DataPipeline |ApacheKafka实战作者胡夕:Apache Kafka监控与调优
https://baijiahao.baidu.com/s?id=1610644333184173190&wfr=spider&for=pc DataPipeline |ApacheK ...
- 利用docker搭建RTMP直播流服务器实现直播
一.rtmp服务器搭建 环境: centos 7.* 1.先安装docker(省略) 2.下载docker容器 docker pull alfg/nginx-rtmp 3.运行容器(记得打开防火墙端口 ...
- CentOS7-Docker 安装 Gitlab
官方教程 https://docs.gitlab.com/omnibus/docker/ 搜索镜像 [root@master ~]# docker search gitlab 拉取镜像 [root@m ...
- SpringBoot整合websocket
1.新增pom依赖 <dependency> <groupId>org.springframework.boot</groupId> <artifactId& ...