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();
    }
}

文件存放位置

模板内容

前端

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

下载成功:

导出

目录
相关文章
|
3月前
|
Python
如何根据Excel某列数据为依据分成一个新的工作表
在处理Excel数据时,我们常需要根据列值将数据分到不同的工作表或文件中。本文通过Python和VBA两种方法实现该操作:使用Python的`pandas`库按年级拆分为多个文件,再通过VBA宏按班级生成新的工作表,帮助高效整理复杂数据。
|
3月前
|
数据采集 数据可视化 数据挖掘
用 Excel+Power Query 做电商数据分析:从 “每天加班整理数据” 到 “一键生成报表” 的配置教程
在电商运营中,数据是增长的关键驱动力。然而,传统的手工数据处理方式效率低下,耗费大量时间且易出错。本文介绍如何利用 Excel 中的 Power Query 工具,自动化完成电商数据的采集、清洗与分析,大幅提升数据处理效率。通过某美妆电商的实战案例,详细拆解从多平台数据整合到可视化报表生成的全流程,帮助电商从业者摆脱繁琐操作,聚焦业务增长,实现数据驱动的高效运营。
|
5月前
|
存储 安全 大数据
网安工程师必看!AiPy解决fscan扫描数据整理难题—多种信息快速分拣+Excel结构化存储方案
作为一名安全测试工程师,分析fscan扫描结果曾是繁琐的手动活:从海量日志中提取开放端口、漏洞信息和主机数据,耗时又易错。但现在,借助AiPy开发的GUI解析工具,只需喝杯奶茶的时间,即可将[PORT]、[SERVICE]、[VULN]、[HOST]等关键信息智能分类,并生成三份清晰的Excel报表。告别手动整理,大幅提升效率!在安全行业,工具党正碾压手动党。掌握AiPy,把时间留给真正的攻防实战!官网链接:https://www.aipyaipy.com,解锁更多用法!
|
3月前
|
JSON Java 数据格式
Spring Boot返回Json数据及数据封装
在Spring Boot中,接口间及前后端的数据传输通常使用JSON格式。通过@RestController注解,可轻松实现Controller返回JSON数据。该注解是Spring Boot新增的组合注解,结合了@Controller和@ResponseBody的功能,默认将返回值转换为JSON格式。Spring Boot底层默认采用Jackson作为JSON解析框架,并通过spring-boot-starter-json依赖集成了相关库,包括jackson-databind、jackson-datatype-jdk8等常用模块,简化了开发者对依赖的手动管理。
378 3
|
7月前
|
JSON Java 数据格式
微服务——SpringBoot使用归纳——Spring Boot返回Json数据及数据封装——封装统一返回的数据结构
本文介绍了在Spring Boot中封装统一返回的数据结构的方法。通过定义一个泛型类`JsonResult&lt;T&gt;`,包含数据、状态码和提示信息三个属性,满足不同场景下的JSON返回需求。例如,无数据返回时可设置默认状态码&quot;0&quot;和消息&quot;操作成功!&quot;,有数据返回时也可自定义状态码和消息。同时,文章展示了如何在Controller中使用该结构,通过具体示例(如用户信息、列表和Map)说明其灵活性与便捷性。最后总结了Spring Boot中JSON数据返回的配置与实际项目中的应用技巧。
540 0
|
7月前
|
JSON Java fastjson
微服务——SpringBoot使用归纳——Spring Boot返回Json数据及数据封装——使用 fastJson 处理 null
本文介绍如何使用 fastJson 处理 null 值。与 Jackson 不同,fastJson 需要通过继承 `WebMvcConfigurationSupport` 类并覆盖 `configureMessageConverters` 方法来配置 null 值的处理方式。例如,可将 String 类型的 null 转为 &quot;&quot;,Number 类型的 null 转为 0,避免循环引用等。代码示例展示了具体实现步骤,包括引入相关依赖、设置序列化特性及解决中文乱码问题。
326 0
|
7月前
|
JSON Java fastjson
微服务——SpringBoot使用归纳——Spring Boot返回Json数据及数据封装——Spring Boot 默认对Json的处理
本文介绍了在Spring Boot中返回Json数据的方法及数据封装技巧。通过使用`@RestController`注解,可以轻松实现接口返回Json格式的数据,默认使用的Json解析框架是Jackson。文章详细讲解了如何处理不同数据类型(如类对象、List、Map)的Json转换,并提供了自定义配置以应对null值问题。此外,还对比了Jackson与阿里巴巴FastJson的特点,以及如何在项目中引入和配置FastJson,解决null值转换和中文乱码等问题。
931 0
|
3月前
|
Python
Excel中如何批量重命名工作表与将每个工作表导出到单独Excel文件
本文介绍了如何在Excel中使用VBA批量重命名工作表、根据单元格内容修改颜色,以及将工作表导出为独立文件的方法。同时提供了Python实现导出工作表的代码示例,适用于自动化处理Excel文档。
|
3月前
|
Python
将Excel特定某列数据删除
将Excel特定某列数据删除
|
消息中间件 Java Kafka
Spring Boot与模板引擎:整合Thymeleaf和FreeMarker,打造现代化Web应用
【8月更文挑战第29天】这段内容介绍了在分布式系统中起到异步通信与解耦作用的消息队列,并详细探讨了三种流行的消息队列产品:RabbitMQ、RocketMQ 和 Kafka。RabbitMQ 是一个基于 AMQP 协议的开源消息队列系统,支持多种消息模型,具有高可靠性及稳定性;RocketMQ 则是由阿里巴巴开源的高性能分布式消息队列,支持事务消息等多种特性;而 Kafka 是 LinkedIn 开源的分布式流处理平台,以其高吞吐量和良好的可扩展性著称。文中还提供了使用这三种消息队列产品的示例代码。
111 0

热门文章

最新文章