使用EasyExcel将MySQL中查询出来的数据下载到Excel文件中

使用EasyExcel将MySQL中查询出来的数据下载到Excel文件中

文章目录

  • 使用EasyExcel将MySQL中查询出来的数据下载到Excel文件中
    • 一,目标描述
    • 二,代码实现
      • (一)代码目录图
      • (二)文件代码及说明
    • 三,补充说明

一,目标描述

我用ptt论坛的数据来做demo演示和说明。数据使用爬虫爬下来,ptt爬虫链接。爬下来的数据是JSON格式,我已经保存到MySQL数据库pttdb的表格Article中。数据库中的数据如下图所示:
使用EasyExcel将MySQL中查询出来的数据下载到Excel文件中_第1张图片
目标是做接口把从Tue Apr 20 19:40:38 2021到Tue Apr 20 19:45:32 2021这五分钟的数据(总共18条)查询出来,并下载到Excel文件中。
下载的结果如下图所示:
使用EasyExcel将MySQL中查询出来的数据下载到Excel文件中_第2张图片
使用springboot做好的接口为get请求,使用范例如下:
http://localhost:8080/download?startTime=Tue%20Apr%2020%2019:40:38%202021&endTime=Tue%20Apr%2020%2019:45:32%202021

二,代码实现

(一)代码目录图

使用EasyExcel将MySQL中查询出来的数据下载到Excel文件中_第3张图片

(二)文件代码及说明

首先是pom.xml,引入需要的mysql驱动依赖、hibernate依赖、阿里巴巴的easyexcel依赖,如下所示:

		<dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <version>8.0.11version>
        dependency>
        <dependency>
            <groupId>org.hibernategroupId>
            <artifactId>hibernate-hikaricpartifactId>
            <version>5.4.17.Finalversion>
        dependency>
        <dependency>
            <groupId>org.hibernategroupId>
            <artifactId>hibernate-ehcacheartifactId>
            <version>5.4.17.Finalversion>
        dependency>
        <dependency>
            <groupId>com.alibabagroupId>
            <artifactId>easyexcelartifactId>
            <version>2.2.7version>
        dependency>

接着是配置文件application.yml,配置好要连接的MySQL数据库,以及JPA的配置:

spring:
  datasource:
    url: jdbc:mysql://127.0.0.1:3306/pttdb?useUnicode=true&characterEncoding=utf-8&useSSL=false&useFastDateParsing=false&serverTimezone=GMT%2B8
    username: ******
    password: ******
    driverClassName: com.mysql.cj.jdbc.Driver

  jpa:
    database-platform: org.hibernate.dialect.MySQL5InnoDBDialect
    show-sql: true
    hibernate:
      ddl-auto: update
      naming:
        physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
    properties:
      hibernate:
        enable_lazy_load_no_trans: true

再看MySQL数据库pttdb中的表格Article,表格的实体类Article.java如下:

package com.example.csdnblog001.demo.model;

import lombok.Data;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import java.util.UUID;

@Data
@Entity
public class Article {
    @Id
    private String articleId = UUID.randomUUID().toString().replace("-", "");

    private String articleTitle;

    private String author;

    private String board;

    @Column(columnDefinition = "longtext")
    private String content;

    private String date;

    private String ip;

    private String messageCount;

    @Column(columnDefinition = "longtext")
    private String messages;

    private String url;

}

对表格进行增删改查的dao层文件ArticleDao.java如下,其中只有一个函数,根据日期范围进行查询,查询出date和date2之间的文章列表:

package com.example.csdnblog001.demo.dao;

import com.example.csdnblog001.demo.model.Article;
import org.springframework.data.jpa.repository.JpaRepository;

import java.util.List;

public interface ArticleDao extends JpaRepository<Article, String> {
    List<Article> findAllByDateBetween(String date, String date2);
}

本次笔记的重头戏要来了,怎么把查询出来的文章数据下载到Excel文件中。这里感谢easyexcel开发者提供的工具,非常方便。参考官方文档web中的写以及GitHub链接
首先是要保存的Excel表格的实体类,见DownloadData.java:

package com.example.csdnblog001.demo.model;
import com.alibaba.excel.annotation.ExcelProperty;
import lombok.Data;

@Data
public class DownloadData {

    @ExcelProperty("布告编号")
    private String articleId;

    @ExcelProperty("标题")
    private String articleTitle;

    @ExcelProperty("作者")
    private String author;

    @ExcelProperty("板块")
    private String board;

    @ExcelProperty("内容")
    private String content;

    @ExcelProperty("布告日期")
    private String date;

    @ExcelProperty("发布者IP")
    private String ip;

    @ExcelProperty("回复统计信息")
    private String messageCount;

    @ExcelProperty("回复")
    private String messages;

    @ExcelProperty("布告链接")
    private String url;

    public DownloadData() {

    }

    public DownloadData(String articleId,
                   String articleTitle,
                   String author,
                   String board,
                   String content,
                   String date,
                   String ip,
                   String messageCount,
                   String messages,
                   String url) {
        this.articleId = articleId;
        this.articleTitle = articleTitle;
        this.author = author;
        this.board = board;
        this.content = content;
        this.date = date;
        this.ip = ip;
        this.messageCount = messageCount;
        this.messages = messages;
        this.url = url;
    }
}

将查询出来的数据保存在DownloadData的列表中,每个DownloadData对象是一篇文章,也是Excel表格中的一行,代码在ArticleServiceImpl.java中:

package com.example.csdnblog001.demo.service;

import com.example.csdnblog001.demo.dao.ArticleDao;
import com.example.csdnblog001.demo.model.Article;
import com.example.csdnblog001.demo.model.DownloadData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class ArticleServiceImpl {
    @Autowired
    ArticleDao articleDao;

    public List<DownloadData> data(String date1, String date2){
        List<DownloadData> list = new ArrayList<DownloadData>();
        List<Article> result = articleDao.findAllByDateBetween(date1,date2);
        for(Article article:result){
            DownloadData data = new DownloadData(article.getArticleId(),
                    article.getArticleTitle(),
                    article.getAuthor(),
                    article.getBoard(),
                    article.getContent(),
                    article.getDate(),
                    article.getIp(),
                    article.getMessageCount(),
                    article.getMessages(),
                    article.getUrl());

            list.add(data);
        }
        return list;
    }
}

最后是下载的restAPI,使用get请求,下载的文件名默认为“下载.xlsx”,代码在DownloadService.java中

package com.example.csdnblog001.demo.rest;

import com.alibaba.excel.EasyExcel;
import com.example.csdnblog001.demo.model.DownloadData;
import com.example.csdnblog001.demo.service.ArticleServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;

@RestController
public class DownloadService {

    @Autowired
    private ArticleServiceImpl articleServiceImpl;

    @GetMapping("/download")
    public void download(HttpServletResponse response,
                         @RequestParam(required = false, defaultValue = "下载") String name,
                         @RequestParam String startTime,
                         @RequestParam String endTime
    ) throws IOException {
        // 这里注意 有同学反应使用swagger 会导致各种问题,请直接用浏览器或者用postman
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode(name, "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), DownloadData.class).sheet("模板").doWrite(articleServiceImpl.data(startTime, endTime));
    }

}

做好的接口http://localhost:8080/download?startTime=Tue%20Apr%2020%2019:40:38%202021&endTime=Tue%20Apr%2020%2019:45:32%202021复制到浏览器中,按enter键即可直接下载。

三,补充说明

本次略去JPA、springboot、MySQL等知识的说明

你可能感兴趣的:(springboot,spring,mysql,java,excel,download)