springboot(八)excle导出导入

x33g5p2x  于2021-12-17 转载在 其他  
字(8.1k)|赞(0)|评价(0)|浏览(682)

概述:

本文使用esaypoi3.2.0模板导入导出,与springdata jpa整合,实现数据库导出数据到excle与excle到入数据库。

      简单适用,能运用于大多数业务场景。

      esaypoi文档地址:http://easypoi.mydoc.io/

数据库:

  1. CREATE TABLE `user` (
  2. `id` int(10) NOT NULL AUTO_INCREMENT,
  3. `name` varchar(20) COLLATE utf8_bin NOT NULL DEFAULT '',
  4. `sex` int(2) NOT NULL DEFAULT '0',
  5. `age` int(3) NOT NULL DEFAULT '0',
  6. `birthday` date DEFAULT NULL,
  7. `create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  8. PRIMARY KEY (`id`)
  9. ) ENGINE=InnoDB AUTO_INCREMENT=16 DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
  10. /*Data for the table `user` */
  11. insert into `user`(`id`,`name`,`sex`,`age`,`birthday`,`create_time`) values (1,'张三',1,12,'2018-02-02','2019-03-21 11:28:21'),(2,'里斯',2,23,'2018-02-23','2019-03-21 11:28:22'),(3,'王二',1,34,'2014-02-03','2019-03-21 11:28:22');

 新建项目:springboot-excle

 打开pom.xml引入依赖

  1. <dependencies>
  2. <!--springdata jpa-->
  3. <dependency>
  4. <groupId>org.springframework.boot</groupId>
  5. <artifactId>spring-boot-starter-data-jpa</artifactId>
  6. </dependency>
  7. <!--web-->
  8. <dependency>
  9. <groupId>org.springframework.boot</groupId>
  10. <artifactId>spring-boot-starter-web</artifactId>
  11. </dependency>
  12. <!--mysql-->
  13. <dependency>
  14. <groupId>mysql</groupId>
  15. <artifactId>mysql-connector-java</artifactId>
  16. <version>5.1.44</version>
  17. </dependency>
  18. <!--druid连接池-->
  19. <dependency>
  20. <groupId>com.alibaba</groupId>
  21. <artifactId>druid-spring-boot-starter</artifactId>
  22. <version>1.1.10</version>
  23. </dependency>
  24. <!--easypoi-->
  25. <dependency>
  26. <groupId>cn.afterturn</groupId>
  27. <artifactId>easypoi-base</artifactId>
  28. <version>3.2.0</version>
  29. </dependency>
  30. <dependency>
  31. <groupId>cn.afterturn</groupId>
  32. <artifactId>easypoi-web</artifactId>
  33. <version>3.2.0</version>
  34. </dependency>
  35. <dependency>
  36. <groupId>cn.afterturn</groupId>
  37. <artifactId>easypoi-annotation</artifactId>
  38. <version>3.2.0</version>
  39. </dependency>
  40. <!--lombok 简化代码-->
  41. <dependency>
  42. <groupId>org.projectlombok</groupId>
  43. <artifactId>lombok</artifactId>
  44. <version>1.16.22</version>
  45. </dependency>
  46. <!--模板引擎-->
  47. <dependency>
  48. <groupId>org.springframework.boot</groupId>
  49. <artifactId>spring-boot-starter-thymeleaf</artifactId>
  50. </dependency>
  51. <!--test-->
  52. <dependency>
  53. <groupId>org.springframework.boot</groupId>
  54. <artifactId>spring-boot-starter-test</artifactId>
  55. <scope>test</scope>
  56. </dependency>
  57. </dependencies>

编辑配置文件:application.properties

  1. #数据库配置
  2. spring.datasource.type= com.alibaba.druid.pool.DruidDataSource
  3. spring.datasource.driver-class-name=com.mysql.jdbc.Driver
  4. spring.datasource.url=jdbc:mysql://127.0.0.1:3306/springboot2?useUnicode=true&characterEncoding=UTF-8
  5. spring.datasource.username=root
  6. spring.datasource.password=123456
  7. #jpa配置
  8. spring.jpa.database=mysql
  9. #是否显示sql
  10. spring.jpa.show-sql=true
  11. # create 每次运行该程序,没有表会新建表,表内有数据会清空
  12. # create-drop 每次程序结束的时候会清空表
  13. # update 每次运行程序,没有表会新建表,表内有数据不会清空,只会更新
  14. # validate 运行程序会校验数据与数据库的字段类型是否相同,不同会报错
  15. spring.jpa.hibernate.ddl-auto=update
  16. #单个文件的大小
  17. spring.servlet.multipart.max-file-size = 100MB
  18. #总文件的大小
  19. spring.servlet.multipart.max-request-size=100MB
  20. #指定日期格式 yyyy-MM-dd HH:mm:ss
  21. spring.jackson.date-format: yyyy-MM-dd HH:mm:ss
  22. #mvc序列化时候时区选择
  23. spring.jackson.time-zone: GMT+8

        注:涉及了excle的文件上传,所以我们要设置,因为springboot默认的单个文件上传大小只有1MB

        

编写User.java类

  1. @Data
  2. @Entity
  3. public class User implements Serializable {
  4. @Id
  5. @GeneratedValue(strategy = GenerationType.IDENTITY)
  6. @Excel(name = "编号")
  7. private int id;
  8. @Excel(name = "姓名")
  9. private String name;
  10. @Excel(name = "性别", replace = {"男_1", "女_2"})
  11. private String sex;
  12. @Excel(name = "年龄")
  13. private int age;
  14. @Excel(name = "出生日期", format = "yyyy-MM-dd", width = 20)
  15. private Date birthday;
  16. @Excel(name = "创建日期", format = "yyyy-MM-dd HH:mm:ss", width = 30)
  17. private Date createTime;
  18. }

     注: 1.@Data注解为lombok插件的,能简化get、set方法的书写。

             2.@Entity 标明bean

             3.@Id  标明当前字段为主键

             4.@GeneratedValue(strategy = GenerationType.IDENTITY)  自增

             5.@Excel 作用到filed上面,是对Excel一列的一个描述

           ** easypoi注解介绍请看**:http://easypoi.mydoc.io/#category_41961

           @Excel中属性介绍:http://easypoi.mydoc.io/#text_186900

编写UserRepository.java类

  1. public interface UserReposity extends JpaRepository<User, Integer> {
  2. }

编写UserService.java类

  1. public interface UserService {
  2. List<User> selectAll();
  3. void add(User user);
  4. void adds(List<User> list);
  5. }

编写UserServiceImpl.java类

  1. @Service
  2. public class UserServiceImpl implements UserService {
  3. @Resource
  4. private UserReposity reposity;
  5. /**
  6. * 查询所有数据
  7. * @return
  8. */
  9. @Override
  10. public List<User> selectAll() {
  11. return reposity.findAll();
  12. }
  13. /**
  14. * 批量添加
  15. * @param list
  16. */
  17. @Override
  18. public void adds(List<User> list) {
  19. reposity.saveAll(list);
  20. }
  21. }

编写excle下载工具类:ExcleUtils.java

  1. public class ExcleUtils {
  2. /**
  3. * excle下载
  4. * @param list 数据集合
  5. * @param title excle表中的标题
  6. * @param sheetName sheet名称
  7. * @param pojoClass pojo类
  8. * @param fileName 生成的文件名
  9. * @param response
  10. */
  11. public static void downloadExcel(List<?> list, String title, String sheetName, Class<?> pojoClass, String fileName, HttpServletResponse response) {
  12. Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(title, sheetName), pojoClass, list);
  13. if (workbook != null) {
  14. try {
  15. response.setCharacterEncoding("UTF-8");
  16. response.setHeader("content-Type", "application/vnd.ms-excel");
  17. response.setHeader("Content-Disposition",
  18. "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
  19. workbook.write(response.getOutputStream());
  20. } catch (IOException e) {
  21. System.out.println(e.getMessage());
  22. }
  23. }
  24. }
  25. }

编写文件配置类:FileConfig.java

  1. public class FileConfig {
  2. //允许上传的excle表格格式
  3. public static final String[] UPLOAD_EXCLE_TYPES ={"xls","xlsx"};
  4. }

编写UserController.java

  1. @Controller
  2. public class UserController {
  3. @Resource
  4. private UserService userService;
  5. /**
  6. * 首页
  7. * @return
  8. */
  9. @GetMapping("/index")
  10. public String index() {
  11. return "index";
  12. }
  13. /**
  14. * excle下载
  15. * @param title
  16. * @param response
  17. */
  18. @GetMapping("/download")
  19. @ResponseBody
  20. public void downLoadExcel(String title,HttpServletResponse response) {
  21. String sheetName="用户";
  22. List<User> userList = userService.selectAll();
  23. ExcleUtils.downloadExcel(userList,title,sheetName,User.class,title+".xlsx",response);
  24. }
  25. /**
  26. * excle导入
  27. * @param file
  28. * @param request
  29. * @return
  30. */
  31. @PostMapping("/upload")
  32. @ResponseBody
  33. public String upload(@RequestParam("fileName") MultipartFile file, HttpServletRequest request){
  34. if(file.isEmpty()){
  35. return "空文件";
  36. }
  37. //获取文件名
  38. String fileName = file.getOriginalFilename();
  39. //获取文件后缀
  40. String type =fileName.indexOf(".") != -1 ? fileName.split("[.]")[1] : null;
  41. //文件格式判断
  42. if (!Arrays.asList(FileConfig.UPLOAD_EXCLE_TYPES).contains(type.toLowerCase())) {
  43. return "文件类型不对";
  44. }
  45. ImportParams params = new ImportParams();
  46. //表格标题所占据的行数,默认0,代表没有标题
  47. params.setTitleRows(1);
  48. //表头所占据的行数行数,默认1,代表标题占据一行
  49. params.setHeadRows(1);
  50. List<User> list;
  51. try {
  52. //excel的数据
  53. list = ExcelImportUtil.importExcel(file.getInputStream(),User.class, params);
  54. //导入数据库
  55. userService.adds(list);
  56. return "success";
  57. } catch (Exception e) {
  58. e.printStackTrace();
  59. return e.getMessage();
  60. }
  61. }
  62. }

      注:excle导入代码中有这么一句

        这里我解释一下titleRows代表的标题占据的行数,headRows对应头部占据的行数。至于什么是标题什么是头部,请看下图就名表了。

          顺便提一下,上面这张图就是我们从数据库导出的excle文件最终效果。而我们导入的时候,要记住不要编号这一列哦,因为编号是我们数据库的主键id,如果你导入存在编号的话就会对已有的数据做修改。导入数据库应该是这样的。没有编号那一列

        还有就是我们的列的标题一定要和我们对象中的@Excle name名称对应哦,也就是这里。一定要对应

编写页面文件:index.html,使用thymeleaf模板引擎

    加入<html xmlns:th="http://www.thymeleaf.org">,才能使thymeleaf语法生效

  1. <!DOCTYPE html>
  2. <html xmlns:th="http://www.thymeleaf.org">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>excle操作</title>
  6. </head>
  7. <body>
  8. <p>-----------------------------------excle导入数据库-----------------------------------</p>
  9. <form action="upload" method="post" enctype="multipart/form-data">
  10. <p>选择文件: <input type="file" name="fileName"/></p>
  11. <p><input type="submit" value="提交"/></p>
  12. </form>
  13. <p>-----------------------------------数据库导出excle-----------------------------------</p>
  14. <a href="/download?title=用户信息表">用户信息表</a>下载
  15. </body>
  16. </html>

源码地址https://gitee.com/xu0123/springboot2

相关文章