SpringBoot下载xlsx模板,导出excel数据

简介: SpringBoot下载xlsx模板,导出excel数据

此文件功能使用SpringBoot来编写,包括写好的前端和后端代码。

使用SpringBoot+POI导出excel数据。

使用SpringBoot导出excel模板文件,防止用户导入错误。

先看是否需要在下载,功能演示都放在这篇文章了:

下载地址:点我下载

项目结构

controller层

package edu.sdjsjxy.jc.controller;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.util.JSONPObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import edu.sdjsjxy.jc.dao.ImportJCFileDataDao;
import edu.sdjsjxy.jc.entity.ImportJCEntity;
import edu.sdjsjxy.jc.entity.JCEntity;
import edu.sdjsjxy.jc.entity.StudentEntity;
import edu.sdjsjxy.jc.service.ImportJCFileDataService;
import edu.sdjsjxy.jc.util.ExcelUtils;
import edu.sdjsjxy.jc.util.FileUtil;
import org.apache.ibatis.annotations.Param;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartException;
import org.springframework.web.multipart.MultipartFile;
import javax.activation.MimetypesFileTypeMap;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
@Controller
@RequestMapping("edu/sdjsjxy/jc/importExcel")
public class ImportExcelController {
    @RequestMapping("")
    public String index() {
        return "jc/importExcel";
    }
    @Autowired
    ImportJCFileDataService importJCFileDataService;
    /**
     * http://127.0.0.1:8080/edu/sdjsjxy/jc/index
     *
     * @param file     文件
     * @param seasonNo 季号
     * @param issue    期号
     * @return
     */
    @RequestMapping(value = "file/upload", method = RequestMethod.POST)
    @ResponseBody
    public String uploadFileCOntroller(@RequestParam("file") MultipartFile file, @RequestParam("seasonNo") int seasonNo, @RequestParam("issue") int issue) {
        if (file == null) {
            return ("上传的文件不允许为空");
        }
        String filename = file.getOriginalFilename();
        try {
            if (filename.length() < 6 || !filename.substring(filename.length() - 5).equals(".xlsx")) {
                return ("文件格式错误");
            }
        } catch (MultipartException m) {
            System.out.println("前台上传错误!");
        }
        try {
            //拿到上传文件中的数据
            List<ImportJCEntity> list = ExcelUtils.excelToShopIdList(file.getInputStream());//解析并拿到上传的数据
            //拿到数据库中的学生数据
            List<StudentEntity> studentDataAll = importJCFileDataService.getDataAll();
            List<JCEntity> jcEntities = new ArrayList<>();
            for (ImportJCEntity ijcEntity : list) {
                for (StudentEntity studentEntity : studentDataAll) {
                    //拿去读过的
                    if (ijcEntity.getStudentName().equals(studentEntity.getStudentName())) {
                        JCEntity jcEntity = new JCEntity();
                        jcEntity.setStudentNumber(studentEntity.getStudentNumber());
                        jcEntity.setPhoneNumber(ijcEntity.getPhoneNumber());
                        jcEntity.setAccessTime(ijcEntity.getAccessTime());
                        jcEntity.setSeasonNo(seasonNo);
                        jcEntity.setIssue(issue);
                        jcEntities.add(jcEntity);
                    }
                }
            }
            System.out.println("读过的:" + jcEntities.size());
            //JCEntity{studentNumber='201911101057', phoneNumber='151****7915', accessTime='17-三月-2020', seasonNo=8, issue=5}
            //正在插入数据
            importJCFileDataService.insertJCFileData(jcEntities);
            System.out.println("插入数据成功");
        } catch (IOException e) {
            System.out.println("上传文件出错,错误代码:" + e.getMessage());
        }
        return ("上传成功!");
    }
    /**
     * http://127.0.0.1:8080/edu/sdjsjxy/jc/index/getJCdata?seasonNo=8&issue=5&className=软测181&pageNum=1&pageSize=10&submitState=false
     *
     * @param pageNum     第几页
     * @param pageSize    每页有多少个
     * @param seasonNo    //第几季
     * @param issue       //第几期
     * @param className   //班级名
     * @param submitState //提交状态:已阅读或为阅读人员
     * @return
     */
    @RequestMapping("getJCdata")
    @ResponseBody
    public String getJCData(@Param("pageNum") Integer pageNum, @Param("pageSize") Integer pageSize, @Param("seasnoNo") Integer seasonNo, @Param("issue") Integer issue, @Param("className") String className, @Param("submitState") String submitState) {
        JSONObject json = new JSONObject();
        if (seasonNo == null || issue == null || className == null) {
            json.put("msg", "参数不允许为空");
            return json.toString();
        }
        System.out.println("查询的状态:" + submitState);
        //利用PageHelper分页查询 注意:这个一定要放查询语句的前一行,否则无法进行分页,因为它对紧随其后第一个sql语句有效
        PageHelper.startPage(pageNum, pageSize);
        if (submitState.equals("true")) {
            List<JCEntity> jcEntityList = importJCFileDataService.getJCSelectTrueData(seasonNo, issue, className);
            PageInfo<JCEntity> pageInfo = new PageInfo<>(jcEntityList);
            json.put("pageInfo", pageInfo);
        } else {
            List<JCEntity> jcEntityList = importJCFileDataService.getJCSelectFalseData(seasonNo, issue, className);
            PageInfo<JCEntity> pageInfo = new PageInfo<>(jcEntityList);
            json.put("pageInfo", pageInfo);
        }
        return json.toString();
    }
    /**
     * 导出
     *
     * @param seasonNo
     * @param issue
     * @param className
     * @param submitState
     * @param response
     * @param request
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/exportJCExcelFileData")
    public String excel2007(@Param("seasnoNo") Integer seasonNo, @Param("issue") Integer issue,
                            @Param("className") String className, @Param("submitState") String submitState,
                            HttpServletResponse response, HttpServletRequest request) {
        JSONObject json = new JSONObject();
        if (seasonNo == null || issue == null || className == null) {
            json.put("msg", "参数不允许为空");
            return json.toString();
        }
        //利用PageHelper分页查询 注意:这个一定要放查询语句的前一行,否则无法进行分页,因为它对紧随其后第一个sql语句有效
        List<JCEntity> jcEntityList = null;
        if (submitState.equals("true")) {
            jcEntityList = importJCFileDataService.getJCSelectTrueData(seasonNo, issue, className);
        } else {
            jcEntityList = importJCFileDataService.getJCSelectFalseData(seasonNo, issue, className);
        }
        Workbook workbook = null;
        try {
            workbook = ExcelUtils.exportDailyBill(jcEntityList, seasonNo, issue);
            response.setHeader("Content-type", "application/vnd.ms-excel");
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + System.currentTimeMillis() + ".xlsx");
            workbook.write(response.getOutputStream());
            workbook.close();
        } catch (IOException e) {
            System.out.println("错误了:" + e.getMessage());
        }
        return json.toString();
    }
    /**
     * 下载导入excel模板
     * @throws IOException
     */
    @RequestMapping(value = "downModel")
    public void download( ) throws IOException {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletResponse response = requestAttributes.getResponse();
        String filename = "导入模板.xlsx";
        // 设置信息给客户端不解析
        String type = new MimetypesFileTypeMap().getContentType(filename);
        // 设置contenttype,即告诉客户端所发送的数据属于什么类型
        response.setHeader("Content-type",type);
        // 设置编码
        String hehe = new String(filename.getBytes("utf-8"), "iso-8859-1");
        // 设置扩展头,当Content-Type 的类型为要下载的类型时 , 这个信息头会告诉浏览器这个文件的名字和类型。
        response.setHeader("Content-Disposition", "attachment;filename=" + hehe);
        FileUtil.download(filename, response);
    }
}

工具类

import javax.servlet.http.HttpServletResponse;
import java.io.*;
public class FileUtil {
    public static void download(String filename, HttpServletResponse res) throws IOException {
        // 发送给客户端的数据
        OutputStream outputStream = res.getOutputStream();
        byte[] buff = new byte[1024];
        BufferedInputStream bis = null;
        // 读取filename
        bis = new BufferedInputStream(new FileInputStream(new File("./file/" + filename)));
        int i = bis.read(buff);
        while (i != -1) {
            outputStream.write(buff, 0, buff.length);
            outputStream.flush();
            i = bis.read(buff);
        }
        bis.close();
        outputStream.close();
    }
}

文件存放位置

模板内容

前端

导入数据之前,先下载模板

下载成功:

导出

目录
相关文章
|
21天前
|
easyexcel
【EasyExcel】第二篇:导出excel文件,导出多个sheet工作空间
【EasyExcel】第二篇:导出excel文件,导出多个sheet工作空间
|
21天前
|
Java
Springboot 导出word,动态填充表格数据
Springboot 导出word,动态填充表格数据
|
4天前
|
Java Apache
java读取excel数据案例
Java代码示例使用Apache POI库读取Excel(example.xlsx)数据。创建FileInputStream和XSSFWorkbook对象,获取Sheet,遍历行和列,根据单元格类型(STRING, NUMERIC, BOOLEAN)打印值。需引入Apache POI库并确保替换文件路径。
7 1
|
11天前
|
easyexcel 数据库
公司大佬对excel导入、导出的封装,那叫一个秒啊
封装公司统一使用的组件的主要目标是为了简化开发人员的调用流程,避免各个项目组重复集成和编写不规范的代码。文中提到对阿里EasyExcel进行了二次封装,提供了导入和导出功能,并支持模板的导入和导出。此外,还处理了读取数据与实际保存数据不一致的情况,通过提供自定义转换器来解决。
36 0
|
12天前
|
数据库
开发指南009-从list导出excel文件
从数据库返回一般是对象的列表,平台底层提供了从list转为excel文件的方法
|
12天前
|
前端开发
开发指南007-导出Excel
平台上开发导出Excel比过去的单体架构要复杂些,因为前端和后台不在一个进程空间里。
|
21天前
|
缓存 前端开发 Java
SpringBoot启动后加载初始化数据
SpringBoot启动后加载初始化数据
|
28天前
|
SQL 数据库连接 数据库
【SQL Server】2. 将数据导入导出到Excel表格当中
【SQL Server】2. 将数据导入导出到Excel表格当中
43 0
|
2月前
|
NoSQL 关系型数据库 MySQL
多人同时导出 Excel 干崩服务器?怎样实现一个简单排队导出功能!
业务诉求:考虑到数据库数据日渐增多,导出会有全量数据的导出,多人同时导出可以会对服务性能造成影响,导出涉及到mysql查询的io操作,还涉及文件输入、输出流的io操作,所以对服务器的性能会影响的比较大;结合以上原因,对导出操作进行排队; 刚开始拿到这个需求,第一时间想到就是需要维护一个FIFO先进先出的队列,给定队列一个固定size,在队列里面的人进行排队进行数据导出,导出完成后立马出队列,下一个排队的人进行操作;还考虑到异步,可能还需要建个文件导出表,主要记录文件的导出情况,文件的存放地址,用户根据文件列表情况下载导出文件。
多人同时导出 Excel 干崩服务器?怎样实现一个简单排队导出功能!