EasyExcel的简单易上手使用
1.EasyExcel 导出功能的实现
首先需要引入EasyExcel相关的依赖包
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>2.2.6</version>
</dependency>
导出的工具类以及代码如下:
package com.wei.weistudy.utils;
import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class EasyExcelUtils<T> {
public void downloadFailedUsingJson(List<T> tableDate, Class<T> classes, String downloadFileName, HttpServletResponse response) throws IOException {
try {
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setCharacterEncoding("utf-8");
String fileName = URLEncoder.encode(downloadFileName, "UTF-8").replaceAll("\\+", "%20");
response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xls");
EasyExcel.write(response.getOutputStream(), classes).autoCloseStream(Boolean.FALSE).sheet("模板")
.doWrite(tableDate);
} catch (Exception e) {
response.reset();
response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
Map<String, String> map = new HashMap<>(2);
map.put("status", "failure");
map.put("message", "下载文件失败" + e.getMessage());
response.getWriter().println(JSON.toJSONString(map));
}
}
}
实体类代码:
package com.wei.weistudy.pojo;
import com.alibaba.excel.annotation.ExcelProperty;
import lombok.Data;
@Data
public class ExportCourse {
@ExcelProperty(value = "课程号",index = 0)
private String cid;
@ExcelProperty(value = "课程名",index = 1)
private String cname;
@ExcelProperty(value = "教师号",index = 2)
private String tid;
}
@Data注解 自动生成 getter、setter方法 需要引入lombok依赖&下载lombok插件配合使用
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.10</version>
<scope>provided</scope>
</dependency>
controller层代码:
package com.wei.weistudy.controller;
import com.wei.weistudy.pojo.Course;
import com.wei.weistudy.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.util.Calendar;
import java.util.List;
@RestController
@RequestMapping(value = "/hello")
public class HelloController {
@Autowired
private UserService userService;
@RequestMapping(value = "/exportCourse")
public void exportCourse(HttpServletResponse response) throws Exception{
userService.exportCourse(response);
}
@RequestMapping(value = "/importCourse")
public void importCourse(MultipartFile file, Long updateSupport){
userService.importCourse(file,updateSupport);
}
}
service层代码:
package com.wei.weistudy.service;
import com.wei.weistudy.pojo.Course;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
public interface UserService {
void exportCourse(HttpServletResponse response) throws IOException;
void importCourse(MultipartFile file, Long updateSupport);
}
serviceImpl层代码(这块只写了导出的,导入的后面写):
package com.wei.weistudy.serviceimpl;
import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wei.weistudy.mapper.UserMapper;
import com.wei.weistudy.pojo.Course;
import com.wei.weistudy.pojo.ExportCourse;
import com.wei.weistudy.service.UserService;
import com.wei.weistudy.utils.EasyExcelUtils;
import com.wei.weistudy.utils.ImportCourse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.concurrent.TimeUnit;
@Service
@Slf4j
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public List<Course> getInfo() {
List<Course> courses = userMapper.getInfo();
return courses;
}
@Override
public void exportCourse(HttpServletResponse response) throws IOException {
Calendar calendar = Calendar.getInstance();
String year = String.valueOf(calendar.get(Calendar.YEAR));
String month = String.valueOf(calendar.get(Calendar.MONTH));
String day = String.valueOf(calendar.get(Calendar.DAY_OF_MONTH));
String title = "学生表" + year + "-" + month + "-" + day;
String fileName = title;
List<Course> info = getInfo();
List<ExportCourse> list = new ArrayList<>();
for (Course course : info) {
ExportCourse exportCourse = new ExportCourse();
BeanUtils.copyProperties(course, exportCourse);
list.add(exportCourse);
}
EasyExcelUtils<ExportCourse> easyExcelUtils = new EasyExcelUtils();
easyExcelUtils.downloadFailedUsingJson(list, ExportCourse.class, fileName, response);
}
}
2.EasyExcel 导入功能的实现
导入功能对应的 controller层、service层、pojo层与导出的一致
导入也有对应的工具类,代码如下:
package com.wei.weistudy.utils;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.wei.weistudy.mapper.UserMapper;
import com.wei.weistudy.pojo.Course;
import com.wei.weistudy.pojo.ExportCourse;
import org.springframework.beans.BeanUtils;
import java.util.ArrayList;
import java.util.List;
public class ImportCourse extends AnalysisEventListener<ExportCourse> {
private UserMapper userMapper;
List<Course> list = new ArrayList<>();
public ImportCourse(UserMapper userMapper) {
this.userMapper = userMapper;
}
@Override
public void invoke(ExportCourse data, AnalysisContext context) {
Course course = new Course();
BeanUtils.copyProperties(data,course);
list.add(course);
}
@Override
public void doAfterAllAnalysed(AnalysisContext context) {
userMapper.insertList(list);
}
}
导入功能对应的serviceImpl代码如下:
package com.wei.weistudy.serviceimpl;
import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wei.weistudy.mapper.UserMapper;
import com.wei.weistudy.pojo.Course;
import com.wei.weistudy.pojo.ExportCourse;
import com.wei.weistudy.service.UserService;
import com.wei.weistudy.utils.EasyExcelUtils;
import com.wei.weistudy.utils.ImportCourse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.concurrent.TimeUnit;
@Service
@Slf4j
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public void importCourse(MultipartFile file) {
try {
BufferedInputStream bufferedInputStream=new BufferedInputStream(file.getInputStream());
EasyExcel.read(bufferedInputStream, ExportCourse.class,new ImportCourse(userMapper)
.sheet()
.doRead();;
} catch (IOException e) {
e.printStackTrace();
}
}
}
以上就是本期EasyExcel导入导出的全部代码了,这些代码仅代表我个人使用成功,如果需要新增其他需求那么需要根据需求去优化代码,若有不足之处请放在评论区我来改正,谢谢大家,让我们共同学习进步吧~加油
|