当前位置:   article > 正文

Springboot整合easyexcel进行excel文件的导入和导出_easyexcelfactory.write(response.getoutputstream(),

easyexcelfactory.write(response.getoutputstream(), user.class).sheet("用户信

1.创建User实体类

  1. package com.lhy.pojo;
  2. import java.io.Serializable;
  3. import io.swagger.annotations.ApiModel;
  4. import io.swagger.annotations.ApiModelProperty;
  5. import lombok.AllArgsConstructor;
  6. import lombok.Data;
  7. import lombok.NoArgsConstructor;
  8. /**
  9. * <p>
  10. * 用户信息
  11. * </p>
  12. *
  13. * @author lhy
  14. * @since 2023-11-28
  15. */
  16. @Data
  17. @AllArgsConstructor
  18. @NoArgsConstructor
  19. @ApiModel(value="User对象", description="用户表")
  20. public class User implements Serializable {
  21. private static final long serialVersionUID = 1L;
  22. @ApiModelProperty(value = "主键id")
  23. private Long id;
  24. @ApiModelProperty(value = "姓名")
  25. private String name;
  26. @ApiModelProperty(value = "性别")
  27. private Integer sex;
  28. @ApiModelProperty(value = "年龄")
  29. private Integer age;
  30. @ApiModelProperty(value = "启用状态")
  31. private String state;
  32. }

2.创建UserExcel实体类

  1. package com.lhy.pojo;
  2. import com.alibaba.excel.annotation.ExcelProperty;
  3. import com.lhy.common.listen.GenderConverter;
  4. import lombok.Data;
  5. @Data
  6. public class UserExcel {
  7. /**
  8. * index指定在excel中列数
  9. */
  10. @ExcelProperty(value = "序号" ,index = 0)
  11. private Long id;
  12. @ExcelProperty(value = "姓名" ,index = 1)
  13. private String name;
  14. @ExcelProperty(value = "性别",index = 2,converter = GenderConverter.class)
  15. private Integer sex;
  16. @ExcelProperty(value = "年龄" ,index = 3)
  17. private int age;
  18. }

3.创建字段属性转换器

  1. package com.lhy.common.listen;
  2. import com.alibaba.excel.converters.Converter;
  3. import com.alibaba.excel.enums.CellDataTypeEnum;
  4. import com.alibaba.excel.metadata.CellData;
  5. import com.alibaba.excel.metadata.GlobalConfiguration;
  6. import com.alibaba.excel.metadata.property.ExcelContentProperty;
  7. public class GenderConverter implements Converter<Integer> {
  8. private static final String MAN = "男";
  9. private static final String WOMAN = "女";
  10. @Override
  11. public Class supportJavaTypeKey() {
  12. // 实体类中对象属性类型
  13. return Integer.class;
  14. }
  15. @Override
  16. public CellDataTypeEnum supportExcelTypeKey() {
  17. // Excel中对应的CellData属性类型
  18. return CellDataTypeEnum.STRING;
  19. }
  20. @Override
  21. public Integer convertToJavaData(CellData cellData, ExcelContentProperty excelContentProperty, GlobalConfiguration globalConfiguration) throws Exception {
  22. // 从Excel中读取数据
  23. String gender = cellData.getStringValue();
  24. // 判断Excel中的值,将其转换为预期的数值
  25. if(MAN.equals(gender)){
  26. return 0;
  27. } else if (WOMAN.equals(gender)) {
  28. return 1;
  29. }
  30. return null;
  31. }
  32. @Override
  33. public CellData convertToExcelData(Integer integer, ExcelContentProperty excelContentProperty, GlobalConfiguration globalConfiguration) throws Exception {
  34. // 判断实体类中获取的值,转换为Excel预期的值,并封装为CellData对象
  35. if(integer == null){
  36. return new CellData("");
  37. } else if(integer == 0){
  38. return new CellData(MAN);
  39. } else if(integer == 1){
  40. return new CellData(WOMAN);
  41. }
  42. return new CellData("");
  43. }
  44. }

4.创建监听器

导入的时候读取excel需要自定义监听器,可以进行处理,或者存储到数据库,导出时不需要

  1. package com.lhy.common.listen;
  2. import com.alibaba.excel.context.AnalysisContext;
  3. import com.alibaba.excel.event.AnalysisEventListener;
  4. import com.alibaba.fastjson.JSON;
  5. import com.lhy.pojo.User;
  6. import com.lhy.pojo.UserExcel;
  7. import com.lhy.service.UserService;
  8. import lombok.extern.slf4j.Slf4j;
  9. import org.springframework.beans.BeanUtils;
  10. import org.springframework.beans.factory.annotation.Autowired;
  11. import org.springframework.stereotype.Component;
  12. import java.util.ArrayList;
  13. import java.util.List;
  14. import java.util.Map;
  15. @Component
  16. @Slf4j
  17. public class ExcelListener extends AnalysisEventListener<UserExcel> {
  18. /**
  19. * 每隔2条存储数据库,实际使用中可以3000条,然后清理list ,方便内存回收
  20. */
  21. private static final int BATCH_COUNT = 2;
  22. //创建list集合封装最终的数据
  23. List<User> userList = new ArrayList();
  24. private static UserService userService;
  25. @Autowired
  26. public void setUserService(UserService userService){
  27. this.userService = userService;
  28. }
  29. @Override
  30. public void invoke(UserExcel userExcel, AnalysisContext analysisContext) {
  31. log.info("解析到一条数据:{}", JSON.toJSONString(userExcel));
  32. User user = new User();
  33. user.setState("Y");
  34. BeanUtils.copyProperties(userExcel,user);
  35. userList.add(user);
  36. if(userList.size() > BATCH_COUNT){
  37. userService.insertBach(userList);
  38. log.info("用户信息存储数据库成功");
  39. userList.clear();
  40. }
  41. }
  42. @Override
  43. public void doAfterAllAnalysed(AnalysisContext analysisContext) {
  44. log.info("解析完所有数据");
  45. }
  46. @Override
  47. public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
  48. System.out.println("表头信息:"+headMap);
  49. }
  50. //一行一行去读取excle内容
  51. }

此处要注意,普通方法上面的注解@Component 和 @Autowired 有时候无法注入service层的对象,会显示null。可以采用注入构造方法的方式解决该问题。

5.代码

此处列出我的service层和controller层的代码,主要就是实现导入和导出

  1. package com.lhy.service.impl;
  2. import com.alibaba.excel.EasyExcel;
  3. import com.alibaba.fastjson.JSON;
  4. import com.lhy.common.exception.MyException;
  5. import com.lhy.common.listen.ExcelListener;
  6. import com.lhy.common.listen.SubjectListener;
  7. import com.lhy.common.listen.UserListener;
  8. import com.lhy.common.result.Result;
  9. import com.lhy.common.result.ResultCodeEnum;
  10. import com.lhy.pojo.Student;
  11. import com.lhy.pojo.User;
  12. import com.lhy.mapper.UserMapper;
  13. import com.lhy.pojo.UserExcel;
  14. import com.lhy.service.UserService;
  15. import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
  16. import org.springframework.beans.BeanUtils;
  17. import org.springframework.stereotype.Service;
  18. import org.springframework.web.multipart.MultipartFile;
  19. import javax.servlet.http.HttpServletResponse;
  20. import java.io.IOException;
  21. import java.io.InputStream;
  22. import java.io.UnsupportedEncodingException;
  23. import java.net.URLEncoder;
  24. import java.util.ArrayList;
  25. import java.util.Date;
  26. import java.util.List;
  27. /**
  28. * <p>
  29. * 用户信息 服务实现类
  30. * </p>
  31. *
  32. * @author lhy
  33. * @since 2023-11-28
  34. */
  35. @Service
  36. public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
  37. @Override
  38. public Boolean insertBach(List<User> users) {
  39. return this.saveBatch(users);
  40. }
  41. @Override
  42. public Result upload(MultipartFile file) {
  43. try {
  44. InputStream inputStream = file.getInputStream();
  45. // String filename = "C:\\Users\\lhy06\\Desktop\\用户信息.xlsx";
  46. EasyExcel.read(inputStream, UserExcel.class, new ExcelListener()).sheet("用户信息").doRead();
  47. inputStream.close();
  48. } catch (IOException e) {
  49. throw new RuntimeException(e);
  50. }
  51. return Result.ok();
  52. }
  53. @Override
  54. public void export(HttpServletResponse response,List<User> users) {
  55. // 设置下载信息
  56. response.setContentType("application/vnd.ms-excel");
  57. response.setCharacterEncoding("utf-8");
  58. // URLEncoder.encode可以防止中文乱码
  59. String fileName= null;
  60. try {
  61. fileName = URLEncoder.encode("用户信息","UTF-8");
  62. } catch (UnsupportedEncodingException e) {
  63. e.printStackTrace();
  64. }
  65. response.setHeader("Content-disposition","attachment;filename="+fileName+".xlsx");
  66. //将User映射为导出的实体类
  67. List<UserExcel> userExcelList=new ArrayList<>();
  68. for (User user : users) {
  69. UserExcel userExcel = new UserExcel();
  70. BeanUtils.copyProperties(user,userExcel);
  71. userExcelList.add(userExcel);
  72. }
  73. //调用方法进行写操作
  74. try {
  75. EasyExcel.write(response.getOutputStream(), UserExcel.class).sheet("用户信息").doWrite(userExcelList);
  76. } catch (IOException e) {
  77. throw new MyException(ResultCodeEnum.DATA_ERROR);
  78. }
  79. }
  80. }
  1. package com.lhy.controller;
  2. import com.alibaba.excel.EasyExcel;
  3. import com.lhy.common.result.Result;
  4. import com.lhy.pojo.User;
  5. import com.lhy.pojo.UserExcel;
  6. import com.lhy.service.UserService;
  7. import org.springframework.beans.factory.annotation.Autowired;
  8. import org.springframework.web.bind.annotation.GetMapping;
  9. import org.springframework.web.bind.annotation.PostMapping;
  10. import org.springframework.web.bind.annotation.RequestMapping;
  11. import org.springframework.web.bind.annotation.RestController;
  12. import org.springframework.web.multipart.MultipartFile;
  13. import javax.servlet.http.HttpServletResponse;
  14. import java.io.IOException;
  15. import java.io.UnsupportedEncodingException;
  16. import java.net.URLEncoder;
  17. import java.util.ArrayList;
  18. import java.util.List;
  19. /**
  20. * <p>
  21. * 用户信息 前端控制器
  22. * </p>
  23. *
  24. * @author lhy
  25. * @since 2023-11-28
  26. */
  27. @RestController
  28. @RequestMapping("//user")
  29. public class UserController {
  30. @Autowired
  31. private UserService userService;
  32. /**
  33. *
  34. * 读取excel文件并存储到数据库
  35. */
  36. @PostMapping("/upload")
  37. public Result upload(MultipartFile file) {
  38. return userService.upload(file);
  39. }
  40. /**
  41. * 下载用户表excel模板
  42. */
  43. @GetMapping("/downLoadExcelTemplate")
  44. public void downLoadTemplate(HttpServletResponse response) throws IOException {
  45. ArrayList<User> users = new ArrayList<>();
  46. users.add(new User(1L, "lhy", 0, 23, "Y"));
  47. userService.export(response, users);
  48. }
  49. /**
  50. * 导出用户表所有信息
  51. */
  52. @GetMapping("/exportAll")
  53. public void exportAll(HttpServletResponse response) throws IOException {
  54. List<User> users = userService.list();
  55. userService.export(response, users);
  56. }
  57. /**
  58. * 导出指定用户信息
  59. */
  60. @GetMapping("/downLoadSelected")
  61. public void downLoadSelected(HttpServletResponse response, List<User> users) throws IOException {
  62. userService.export(response, users);
  63. }
  64. }

导出的时候可以下载到本地,也可以根据浏览器的响应进行下载。

本文内容由网友自发贡献,转载请注明出处:https://www.wpsshop.cn/w/我家小花儿/article/detail/476395
推荐阅读
相关标签
  

闽ICP备14008679号