更多的easyPOI资源的网在easypoi的官网。

1 在pom.xml中添加依赖

<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>

2 工具类

package com.hhsj.tools.excelUtils;

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.io.InputStream;
import java.net.URL;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException; public class ExcelUtils {
/**
* excel 导出
*
* @param list 数据
* @param title 标题
* @param sheetName sheet名称
* @param pojoClass pojo类型
* @param fileName 文件名称
* @param isCreateHeader 是否创建表头
* @param response
*/
public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass, String fileName, boolean isCreateHeader, HttpServletResponse response) throws IOException {
ExportParams exportParams = new ExportParams(title, sheetName, ExcelType.XSSF);
exportParams.setCreateHeadRows(isCreateHeader);
defaultExport(list, pojoClass, fileName, response, exportParams);
} /**
* excel 导出
*
* @param list 数据
* @param title 标题
* @param sheetName sheet名称
* @param pojoClass pojo类型
* @param fileName 文件名称
* @param response
*/
public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass, String fileName, HttpServletResponse response) throws IOException {
defaultExport(list, pojoClass, fileName, response, new ExportParams(title, sheetName, ExcelType.XSSF));
} /**
* excel 导出
*
* @param list 数据
* @param pojoClass pojo类型
* @param fileName 文件名称
* @param response
* @param exportParams 导出参数
*/
public static void exportExcel(List<?> list, Class<?> pojoClass, String fileName, ExportParams exportParams, HttpServletResponse response) throws IOException {
defaultExport(list, pojoClass, fileName, response, exportParams);
} /**
* excel 导出
*
* @param list 数据
* @param fileName 文件名称
* @param response
*/
public static void exportExcel(List<Map<String, Object>> list, String fileName, HttpServletResponse response) throws IOException {
defaultExport(list, fileName, response);
} /**
* 默认的 excel 导出
*
* @param list 数据
* @param pojoClass pojo类型
* @param fileName 文件名称
* @param response
* @param exportParams 导出参数
*/
private static void defaultExport(List<?> list, Class<?> pojoClass, String fileName, HttpServletResponse response, ExportParams exportParams) throws IOException {
Workbook workbook = ExcelExportUtil.exportExcel(exportParams, pojoClass, list);
downLoadExcel(fileName, response, workbook);
} /**
* 默认的 excel 导出
*
* @param list 数据
* @param fileName 文件名称
* @param response
*/
private static void defaultExport(List<Map<String, Object>> list, String fileName, HttpServletResponse response) throws IOException {
Workbook workbook = ExcelExportUtil.exportExcel(list, ExcelType.HSSF);
downLoadExcel(fileName, response, workbook);
} /**
* 下载
*
* @param fileName 文件名称
* @param response
* @param workbook excel数据
*/
private static void downLoadExcel(String fileName, HttpServletResponse response, Workbook workbook) throws IOException {
try {
response.setCharacterEncoding("UTF-8");
response.setHeader("content-Type", "application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName,"UTF-8") + "." + ExcelTypeEnum.XLSX.getValue());
workbook.write(response.getOutputStream());
} catch (Exception e) {
throw new IOException(e.getMessage());
}
} /**
* excel 导入
*
* @param filePath excel文件路径
* @param titleRows 标题行
* @param headerRows 表头行
* @param pojoClass pojo类型
* @param <T>
* @return
*/
public static <T> List<T> importExcel(String filePath, Integer titleRows, Integer headerRows, Class<T> pojoClass) throws IOException {
if (StringUtils.isBlank(filePath)) {
return null;
}
ImportParams params = new ImportParams();
params.setTitleRows(titleRows);
params.setHeadRows(headerRows);
params.setNeedSave(true);
params.setSaveUrl("/excel/");
try {
return ExcelImportUtil.importExcel(new File(filePath), pojoClass, params);
} catch (NoSuchElementException e) {
throw new IOException("模板不能为空");
} catch (Exception e) {
throw new IOException(e.getMessage());
}
} /**
* excel 导入
*
* @param file excel文件
* @param pojoClass pojo类型
* @param <T>
* @return
*/
public static <T> List<T> importExcel(MultipartFile file, Class<T> pojoClass) throws IOException {
return importExcel(file, 1, 1, pojoClass);
} /**
* excel 导入
*
* @param file excel文件
* @param titleRows 标题行
* @param headerRows 表头行
* @param pojoClass pojo类型
* @param <T>
* @return
*/
public static <T> List<T> importExcel(MultipartFile file, Integer titleRows, Integer headerRows, Class<T> pojoClass) throws IOException {
return importExcel(file, titleRows, headerRows, false, pojoClass);
} /**
* excel 导入
*
* @param file 上传的文件
* @param titleRows 标题行
* @param headerRows 表头行
* @param needVerfiy 是否检验excel内容
* @param pojoClass pojo类型
* @param <T>
* @return
*/
public static <T> List<T> importExcel(MultipartFile file, Integer titleRows, Integer headerRows, boolean needVerfiy, Class<T> pojoClass) throws IOException {
if (file == null) {
return null;
}
try {
return importExcel(file.getInputStream(), titleRows, headerRows, needVerfiy, pojoClass);
} catch (Exception e) {
throw new IOException(e.getMessage());
}
} /**
* excel 导入
*
* @param inputStream 文件输入流
* @param titleRows 标题行
* @param headerRows 表头行
* @param needVerfiy 是否检验excel内容
* @param pojoClass pojo类型
* @param <T>
* @return
*/
public static <T> List<T> importExcel(InputStream inputStream, Integer titleRows, Integer headerRows, boolean needVerfiy, Class<T> pojoClass) throws IOException {
if (inputStream == null) {
return null;
}
ImportParams params = new ImportParams();
params.setTitleRows(titleRows);
params.setHeadRows(headerRows);
params.setSaveUrl("/excel/");
params.setNeedSave(true);
params.setNeedVerfiy(needVerfiy);
try {
return ExcelImportUtil.importExcel(inputStream, pojoClass, params);
} catch (NoSuchElementException e) {
throw new IOException("excel文件不能为空");
} catch (Exception e) {
throw new IOException(e.getMessage());
}
} /**
* Excel 类型枚举
*/
enum ExcelTypeEnum {
XLS("xls"), XLSX("xlsx");
private String value; ExcelTypeEnum(String value) {
this.value = value;
} public String getValue() {
return value;
} public void setValue(String value) {
this.value = value;
}
}
}

3 实体类

package com.hhsj.entity.salaryWorkAttendance;

import cn.afterturn.easypoi.excel.annotation.Excel;
import com.fasterxml.jackson.annotation.JsonFormat;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.hibernate.annotations.GenericGenerator;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener; import javax.persistence.*;
import java.util.Date; @Data
@Entity
@EqualsAndHashCode(callSuper = false)
@Table(name = "c_work_attendance")
@EntityListeners(AuditingEntityListener.class)
@ApiModel(value = "WorkAttendance" ,description = "考勤信息表")
public class WorkAttendance {
@Id
@GeneratedValue(generator = "system-uuid")
@GenericGenerator(name = "system-uuid", strategy = "uuid")
private String id; private String corpId; @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
@CreatedDate
private Date createTime; @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
@LastModifiedDate
private Date updateTime; @Excel(name = "员工姓名",orderNum = "0",width = 15)
@ApiModelProperty(value = "员工姓名")
private String employeeName; @Excel(name = "岗位",orderNum = "1",width = 15)
@ApiModelProperty(value = "岗位")
private String post; @Excel(name = "对应器械",orderNum = "2",width = 15)
@ApiModelProperty(value = "对应器械")
private String correspondingApparatus; @Excel(name = "关联项目",orderNum = "3",width = 15)
@ApiModelProperty(value = "关联项目")
private String relatedItems; @Excel(name = "装卸点选择",orderNum = "4",width = 15)
@ApiModelProperty(value = "装卸点选择")
private String pointChoice; @Excel(name = "考勤时间",orderNum = "5",format = "yyyy-MM-dd HH:mm:ss",width = 25)
@ApiModelProperty(value = "考勤时间")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date attendanceTime; @Excel(name = "考勤类型",orderNum = "7",width = 15)
@ApiModelProperty(value = "考勤类型")
private String attendanceType; @Excel(name = "位置",orderNum = "8",width = 15)
@ApiModelProperty(value = "位置")
private String position; @ApiModelProperty(value = "现场照片")
private String img; }

4 具体操作

package com.hhsj.service.salaryWorkAttendance.impl;

import com.hhsj.common.Result;
import com.hhsj.entity.salaryWorkAttendance.WorkAttendance;
import com.hhsj.exception.NormalException;
import com.hhsj.repository.salaryWorkAttendance.WorkAttendanceRepository;
import com.hhsj.request.salaryWorkAttendance.WorkAttendanceRequest;
import com.hhsj.service.salaryWorkAttendance.IWorkAttendanceService;
import com.hhsj.token.TokenUtils;
import com.hhsj.tools.excelUtils.ExcelUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile; import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects; @Service
public class WorkAttendanceServiceImpl implements IWorkAttendanceService {
@Autowired
private WorkAttendanceRepository workAttendanceRepository; @Autowired
private TokenUtils tokenUtils; @Override
@Transactional(readOnly = false,rollbackFor = Exception.class)
public Result<String> workAttendanceImport(MultipartFile file) {
String corpId = tokenUtils.getCurrentCorpId();
//获取上传文件的名称
String fileName = file.getOriginalFilename();
if (!Objects.requireNonNull(fileName).matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
throw new NormalException("上传文件格式不正确");
}
try {
List<WorkAttendance> attendances = ExcelUtils.importExcel(file,WorkAttendance.class);
if (attendances != null && attendances.size() != 0){
for (WorkAttendance attendance : attendances) {
attendance.setCorpId(corpId);
workAttendanceRepository.save(attendance);
}
} }catch (Exception e){
throw new NormalException("上传失败");
}
return Result.<String>builder().success().message("上传成功").build();
} @Override
public Result<String> workAttendanceExport(HttpServletResponse response) {
WorkAttendance workAttendance = new WorkAttendance();
workAttendance.setAttendanceTime(new Date());
List<WorkAttendance> list = new ArrayList<>();
list.add(workAttendance);
try {
ExcelUtils.exportExcel(list,"考勤模板","考勤模板",WorkAttendance.class,"kaoqin",response);
} catch (IOException e) {
throw new NormalException("模板下载失败");
}
return Result.<String>builder().success().message("导出成功").build();
}
}

easyPOI使用的更多相关文章

  1. SpringBoot加Poi仿照EasyPoi实现Excel导出

    POI提供API给Java程序对Microsoft Office格式档案读和写的功能,详细功能可以直接查阅API,因为使用EasyPoi过程中总是缺少依赖,没有搞明白到底是什么坑,索性自己写一个简单工 ...

  2. 使用EasyPOI导出excel示例

    package com.mtoliv.sps.controller; import java.io.IOException; import java.io.OutputStream; import j ...

  3. EXCE 表格导入导出遇到问题(easypoi)

    使用Easypoi进行excel表格的导入导出遇到的问题: 1.导出时候打开文件一直遇乱码,主要的原因就是我在实体类没有进行给每个字段进行注解,就会导致每个字段找不到对应的汉字表头,所以一定不要忘了导 ...

  4. spring boot + easypoi两行代码excel导入导出

    easypoi封装了poi让我们能够非常简单的实现Excel导出,Excel模板导出,Excel导入,Word模板导出等,具体可见官网:http://www.afterturn.cn/. 我这边实现了 ...

  5. SpringBoot2.x使用EasyPOI导入Excel浅谈

    SpringBoot2.x使用EasyPOI导入Excel浅谈 平时经常遇到客户要帮忙导入一些数据到数据库中,有些数据比较多有时候手动录入就会很耗时间,所以就自己写一个Excel导入的demo记录一下 ...

  6. java利用EasyPoi实现Excel导出功能

    easypoi功能如同名字easy,主打的功能就是容易,让一个没见接触过poi的人员 就可以方便的写出Excel导出,Excel模板导出,Excel导入,Word模板导出,通过简单的注解和模板 语言( ...

  7. 关于EasyPoi导出Excel

    如果你觉得Easypoi不好用,喜欢用传统的poi,可以参考我的这篇博客:Springmvc导出Excel(maven) 当然了,万变不离其宗.Easypoi的底层原理还是poi.正如MyBatis ...

  8. java通过POI和easypoi实现Excel的导出

    前言 在工作经常会遇到excel导出报表的功能,自己也做过一些,然后在项目里看到同事封装的一个excel导出工具类,着实不错,拿来分享一下.然后,又在网上看到一个使用easypoi实现cxcel导出的 ...

  9. 使用easypoi导出excel

    EasyPOI是在jeecg的poi模块基础上,继续开发独立出来的,可以说是2.0版本,EasyPoi封装的目的和jeecg一致,争取让大家write less do more ,在这个思路上easy ...

  10. 【springboot+easypoi】一行代码搞定excel导入导出

    原文:https://www.jianshu.com/p/5d67fb720ece 开发中经常会遇到excel的处理,导入导出解析等等,java中比较流行的用poi,但是每次都要写大段工具类来搞定这事 ...

随机推荐

  1. Scala 面向对象(九):特质(接口) 二

    1 带有具体实现的特质 说明:和Java中的接口不太一样的是特质中的方法并不一定是抽象的,也可以有非抽象方法(即:实现了的方法). 2 带有特质的对象,动态混入 1)除了可以在类声明时继承特质以外,还 ...

  2. 数据分析06 /pandas高级操作相关案例:人口案例分析、2012美国大选献金项目数据分析

    数据分析06 /pandas高级操作相关案例:人口案例分析.2012美国大选献金项目数据分析 目录 数据分析06 /pandas高级操作相关案例:人口案例分析.2012美国大选献金项目数据分析 1. ...

  3. Django之 admin组件

    本节内容 路由系统 models模型 admin  views视图 template模板 Django Admin介绍 admin 是django 自带的用来让你进行数据库管理的web app. 提供 ...

  4. JavaScript之setinterval的具体使用

    关于setInterval在api文档中也有很详细的解释,比如下面那两个: setInterval() 方法可按照指定的周期(以毫秒计)来调用函数或计算表达式. setInterval() 方法会不停 ...

  5. GPO - Folder Mapping via GPO

    Create a Group Policy on AD DC Server. The GPO policy will come into effect on the next login, or us ...

  6. OceanBase安装和使用

    链接 https://mp.weixin.qq.com/s?spm=a2c6h.12873639.0.0.41f92c9bH5FL2Y&__biz=MzU3OTc2MDQxNg==&m ...

  7. [Abp vNext 源码分析] - 23. 二进制大对象系统(BLOB)

    一.简介 ABP vNext 在 v 2.9.x 版本当中添加了 BLOB 系统,主要用于存储大型二进制文件.ABP 抽象了一套通用的 BLOB 体系,开发人员在存储或读取二进制文件时,可以忽略具体实 ...

  8. 各版本arm-gcc区别与安装【转】

    转自:https://www.jianshu.com/p/fd0103d59d8e arm-linux-gcc.arm-none-eabi-gcc.arm-eabi-gcc.arm-none-linu ...

  9. .NET CORE HttpClient使用

    自从HttpClient诞生依赖,它的使用方式一直备受争议,framework版本时代产生过相当多经典的错误使用案例,包括Tcp链接耗尽.DNS更改无感知等问题.有兴趣的同学自行查找研究.在.NETC ...

  10. jenkins初学部分笔记网站

    https://www.cnblogs.com/wfd360/p/11314697.html 自动化部署详细教程 https://blog.csdn.net/weixin_41948075/artic ...