easyExcel的web用法
依赖
<?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 http://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.6.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>easyexcel</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>easyexcel</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.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.1.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.baomidou/mybatis-plus-boot-starter -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.1.2</version>
</dependency>
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.28</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.16</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.8</version>
<scope>provided</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba/easyexcel -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>1.1.2-beat1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/cn.hutool/hutool-all -->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>4.5.16</version>
</dependency>
<dependency>
<groupId>com.battcn</groupId>
<artifactId>swagger-spring-boot-starter</artifactId>
<version>2.1.5-RELEASE</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
创建实体类
@Data
@EqualsAndHashCode(callSuper = true)
@Accessors(chain = true)
public class User extends BaseEntity {
private static final long serialVersionUID = 1L;
@TableId(value = "id",type = IdType.AUTO)
private Integer id;
private String userName;
private Integer age;
private String sex;
private String address;
private String phone;
private String hobby;
private Date birthday;
private LocalDateTime createTime;
}
mapper ,service,controller 使用mybatisplus自动生成
创建 导入module
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.metadata.BaseRowModel;
import lombok.Data;
import java.util.Date;
/**
* @author lcm
*/
@Data
public class UserReadModule extends BaseRowModel {
@ExcelProperty(value = "用户名",index = 0)
private String userName;
@ExcelProperty(value = "年龄",index = 1)
private Integer age;
@ExcelProperty(value = "性别",index = 2)
private String sex;
@ExcelProperty(value = "家庭住址",index = 3)
private String address;
@ExcelProperty(value = "手机电话",index = 4)
private String phone;
@ExcelProperty(value = "业余爱好",index = 5)
private String hobby;
@ExcelProperty(value = "出生日期",index = 6,format = "yyyy-MM-dd")
private Date birthday;
}
创建导出module
@Data
public class UserWriteModule extends BaseRowModel {
private Integer id;
@ExcelProperty(value = "用户名",index = 0)
private String userName;
@ExcelProperty(value = "年龄",index = 1)
private Integer age;
@ExcelProperty(value = "性别",index = 2)
private String sex;
@ExcelProperty(value = "家庭住址",index = 3)
private String address;
@ExcelProperty(value = "手机电话",index = 4)
private String phone;
@ExcelProperty(value = "业余爱好",index = 5)
private String hobby;
@ExcelProperty(value = "出生日期",index = 6)
private LocalDate birthday;
}
创建Excel监听器 监听导入的数据 进行数据处理
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.example.easyexcel.work.dto.UserReadModule;
import com.example.easyexcel.work.entity.User;
import com.example.easyexcel.work.service.IUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
/**
* 监听器 监听Excel导入时会去读取Excel的内容
* @author lcm
*/
@Component
public class ExcelListener extends AnalysisEventListener {
@Autowired
private IUserService userService;
private List<UserReadModule> userReadModuleList = new ArrayList<>();
public ExcelListener(){};
public ExcelListener(IUserService service){
this.userService = service;
}
/**
* 该方法是逐条读取Excel 的内容
* @param object
* @param context
*/
@Override
public void invoke(Object object, AnalysisContext context) {
Integer currentRowNum = context.getCurrentRowNum();
if (currentRowNum!=0){
System.out.println(object);
UserReadModule userReadModule = (UserReadModule) object;
userReadModuleList.add(userReadModule);
}
}
/**
* 将所有的内容读取之后的方法
* @param context
*/
@Override
public void doAfterAllAnalysed(AnalysisContext context) {
System.out.println("所有数据读取完毕");
List<User> list = new ArrayList<>();
userReadModuleList.forEach(userReadModule -> {
User user = new User();
BeanUtils.copyProperties(userReadModule,user);
list.add(user);
});
userService.saveBatch(list);
}
}
excel工具类
import cn.hutool.core.util.URLUtil;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.BaseRowModel;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.support.ExcelTypeEnum;
import org.apache.poi.util.StringUtil;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
public class ExcelUtils {
public static void exportModule(String filename, HttpServletResponse response, Class<? extends BaseRowModel> classModule, List<? extends BaseRowModel> data) throws IOException {
String fileName = new String((filename+ new SimpleDateFormat("yyyyMMdd").format(new Date()))
.getBytes(), "UTF-8");
ServletOutputStream out = response.getOutputStream();
response.setContentType("multipart/form-data");
response.setCharacterEncoding("utf-8");
response.setHeader("Content-disposition", "attachment;filename="+ URLUtil.encode(fileName, StringUtil.UTF8) +".xlsx");
ExcelWriter writer = new ExcelWriter(out, ExcelTypeEnum.XLSX, true);
Sheet sheet = new Sheet(1, 0, classModule, filename, null);
sheet.setAutoWidth(Boolean.TRUE);
writer.write(data,sheet);
writer.finish();
out.close();
}
public static void exportMap(String filename, HttpServletResponse response, List<List<String>> headList, List<? extends BaseRowModel> data) throws IOException {
String fileName = new String((filename+ new SimpleDateFormat("yyyyMMdd").format(new Date()))
.getBytes(), "UTF-8");
ServletOutputStream out = response.getOutputStream();
response.setContentType("multipart/form-data");
response.setCharacterEncoding("utf-8");
response.setHeader("Content-disposition", "attachment;filename="+ URLUtil.encode(fileName, StringUtil.UTF8) +".xlsx");
ExcelWriter writer = new ExcelWriter(out, ExcelTypeEnum.XLSX, true);
Sheet sheet = new Sheet(1,0);
sheet.setAutoWidth(Boolean.TRUE);
sheet.setHead(headList);
writer.write(data,sheet);
writer.finish();
out.close();
}
}
controller层实现web端操作
package com.example.filehandling.easyexcel.controller;
import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.metadata.Sheet;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.example.filehandling.easyexcel.dto.UserReadModule;
import com.example.filehandling.easyexcel.dto.UserWriteModule;
import com.example.filehandling.easyexcel.entity.User;
import com.example.filehandling.easyexcel.listener.ExcelListener;
import com.example.filehandling.easyexcel.mapper.UserMapper;
import com.example.filehandling.easyexcel.service.IUserService;
import com.example.filehandling.util.ExcelUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
/**
* <p>
* 前端控制器
* </p>
*
* 使用阿里巴巴开源项目 easy excel
* 项目源码:https://github.com/alibaba/easyexcel
*
*
* @author lcm
* @since 2019-07-04
*/
@Api(description = "easyExcel 的用法")
@RestController
@RequestMapping("/work/user")
public class UserController {
@Autowired
private IUserService userService;
@Autowired
private UserMapper userMapper;
@Autowired
private ExcelListener excelListener;
@ApiOperation(value = "下载模板")
@GetMapping("downLoadTemplate")
public void downLoadTemplate(HttpServletResponse response) throws IOException {
//第三个参数new ArrayList() 是我们需要填充的数据
ExcelUtils.exportModule("导入模板",response, UserWriteModule.class,new ArrayList<>());
}
@ApiOperation("Excel导入")
@PostMapping("uploadData")
public Object uploadData(MultipartFile file) throws IOException {
InputStream inputStream = file.getInputStream();
EasyExcelFactory.readBySax(inputStream, new Sheet(1, 1, UserReadModule.class), excelListener);
inputStream.close();
return "success";
}
@ApiOperation("Excel导出使用module")
@GetMapping("export")
public void export(HttpServletResponse response) throws IOException {
List<UserWriteModule> userWriteModules = userMapper.exportList(new QueryWrapper().select("*"));
ExcelUtils.exportModule("用户信息",response,UserWriteModule.class,userWriteModules);
}
/**
* 不使用module
* @param response
* @throws IOException
*/
@ApiOperation("Excel导出不适用module")
@GetMapping("exportMap")
public void exportMap(HttpServletResponse response) throws IOException {
List<UserWriteModule> userWriteModules = userMapper.exportList(new QueryWrapper().select("*"));
ExcelUtils.exportMap("用户信息",response,getHeadList(),userWriteModules);
}
public List<List<String>> getHeadList(){
List<List<String>> headList = new ArrayList<>();
List<String> dataHead = new ArrayList<>();
dataHead.add("用户姓名");
dataHead.add("年龄");
dataHead.add("性别");
dataHead.add("地址");
dataHead.add("手机号");
dataHead.add("兴趣");
dataHead.forEach(s -> {
ArrayList<String> objects = new ArrayList<>();
objects.add(s);
headList.add(objects);
});
return headList;
}
@ApiOperation("查询列表")
@GetMapping("get")
public Object get(@RequestParam String name){
return userService.list(Wrappers.<User>lambdaQuery().eq(User::getUserName,name));
}
}