SpringBoot导入和导出Csv文件(二十八)下

简介: SpringBoot导入和导出Csv文件(二十八)下

四. SpringBoot 实现 Csv文件的导入和导出

按照上一章节的模式,进行修改.


四.一 前端页面

<!doctype html>
<!--注意:引入thymeleaf的名称空间-->
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta http-equiv="Content-Type"content="text/html;charset=UTF-8">
    <title>文件上传</title>
    <link rel="StyleSheet" href="webjars/bootstrap/3.4.1/css/bootstrap.css" type="text/css">
</head>
<body class="container">
<p class="h1">导入文件</p>
<form  action="uploadCsv" method="post" enctype="multipart/form-data">
    <div class="form-group">
        <div class="custom-file">
            <input type="file" class="custom-file-input" id="file" name="file">
            <label class="file-label" for="file">选择文件</label>
        </div>
    </div>
    <button type="submit" class="btn btn-primary">上传</button>
</form>
<p class="h1">文件导出</p>
<a href="downloadCsv">导出Csv文件</a>
<script type="text/javascript" src="webjars/jquery/3.5.1/jquery.js"></script>
<script type="text/javascript" src="webjars/bootstrap/3.4.1/js/bootstrap.js"></script>
</body>
</html>

image.png


四.二 Csv文件导入

四.二.一 导入逻辑处理

/**
     * 上传Excel文件,获取文件里面的内容.
     * @date 2021/11/4 21:12
     * @author zk_yjl
     * @return
     */
    @PostMapping("/uploadCsv")
    @ResponseBody
    public String uploadCsv(@RequestParam MultipartFile file) throws IOException {
        String realPath =uploadFilePath;
        File newFile = new File(realPath);
        // 如果文件夹不存在、则新建
        if (!newFile.exists()){
            newFile.mkdirs();
        }
        // 上传
        File uploadFile=new File(newFile, file.getOriginalFilename());
        file.transferTo(uploadFile);
        //读取文件信息,主要是这一行
        List<User> userList = CsvUtil.getReader().read(new FileReader(uploadFile), User.class);
        userList.forEach(n->{
            log.info("输出内容:>>>"+n);
            //可以进行具体的业务操作
        });
        String uploadPath=realPath+"/"+file.getOriginalFilename();
        return "上传文件成功,地址为:"+uploadPath;
    }


四.二.二 导入上传测试

将 header.csv 文件进行上传

image.png



后端控制台 将 文件中的内容打印出来


image.png


四.三 Csv文件导出

四.三.一 导出文件逻辑处理

/**
     * 下载Excel文件
     * @date 2021/11/4 21:12
     * @author zk_yjl
     * @return
     */
    @GetMapping("/downloadCsv")
    @ResponseBody
    public void downloadCsv(HttpServletResponse response) throws IOException {
        //1. 通过传入的参数,和相关的业务代码逻辑处理,获取相应的数据.
        //2. 将数据进行转换,转换成 List<User> 的形式.
        List<User> dataList= DataUtil.createDataList("两个蝴蝶飞");
        //将数据进行下载.
        // 这里注意 有同学反应使用swagger 会导致各种问题,请直接用浏览器或者用postman
        try {
            //响应类型
            response.setContentType("multipart/form-data");
            response.setCharacterEncoding("utf-8");
            //进行下载
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("员工表", "UTF-8").replaceAll("\\+", "%20");
            //响应的是  .csv 文件的后缀
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".csv");
            // 这里需要设置不关闭流
            String filePath=uploadFilePath+File.separator+fileName+".csv";
            File file=new File(filePath);
            if(!file.exists()){
                file.createNewFile();
            }
            //将数据,写入到 文件里面。 主要是这一行代码逻辑
            CsvUtil.getWriter(file, Charset.forName("UTF-8")).writeBeans(dataList).close();
            downloadFile(response,file);
            //将该文件删除
            file.delete();
        } catch (Exception e) {
            // 重置response
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            Map<String, String> map = new HashMap<String, String>();
            map.put("status", "failure");
            map.put("message", "下载文件失败" + e.getMessage());
            JSONObject jsonObject=new JSONObject();;
            response.getWriter().println(jsonObject.toString());
        }
    }
    /**
     * @return boolean
     * @Description 下载文件
     * @Param response,file
     **/
    public boolean downloadFile(HttpServletResponse response, File file) {
        FileInputStream fileInputStream = null;
        BufferedInputStream bufferedInputStream = null;
        OutputStream os = null;
        try {
            fileInputStream = new FileInputStream(file);
            bufferedInputStream = new BufferedInputStream(fileInputStream);
            os = response.getOutputStream();
            //MS产本头部需要插入BOM
            //如果不写入这几个字节,会导致用Excel打开时,中文显示乱码
            os.write(new byte[]{(byte) 0xEF, (byte) 0xBB, (byte) 0xBF});
            byte[] buffer = new byte[1024];
            int i = bufferedInputStream.read(buffer);
            while (i != -1) {
                os.write(buffer, 0, i);
                i = bufferedInputStream.read(buffer);
            }
            return true;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //关闭流
            if (os != null) {
                try {
                    os.flush();
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bufferedInputStream != null) {
                try {
                    bufferedInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fileInputStream != null) {
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            file.delete();
        }
        return false;
    }

四.三.二 导出测试

点击导出文件,可以进行相应的下载.

image.png


相关文章
|
8月前
|
XML Java Maven
springboot-多环境配置文件
本文介绍了如何创建开发和生产环境的配置文件,并在IDEA和Maven中进行配置。开发环境中,通过设置profile为`dev`来指定配置文件;生产环境中,使用Maven命令参数`-Pprod`打包并指定配置文件。公共配置可放在`application.yml`中统一管理。日志配置需确保`logback-spring.xml`中的profile正确,以保证日志正常输出。
481 4
springboot-多环境配置文件
|
9月前
|
存储 前端开发 Java
Springboot静态资源映射及文件映射
在Spring Boot项目中,为了解决前端访问后端存储的图片问题,起初尝试通过静态资源映射实现,但发现这种方式仅能访问打包时已存在的文件。对于动态上传的图片(如头像),需采用资源映射配置,将特定路径映射到服务器上的文件夹,确保新上传的图片能即时访问。例如,通过`addResourceHandler(&quot;/img/**&quot;).addResourceLocations(&quot;file:E:\\myProject\\forum_server\\&quot;)`配置,使前端可通过URL直接访问图片。
541 0
Springboot静态资源映射及文件映射
|
8月前
|
前端开发 Cloud Native Java
Java||Springboot读取本地目录的文件和文件结构,读取服务器文档目录数据供前端渲染的API实现
博客不应该只有代码和解决方案,重点应该在于给出解决方案的同时分享思维模式,只有思维才能可持续地解决问题,只有思维才是真正值得学习和分享的核心要素。如果这篇博客能给您带来一点帮助,麻烦您点个赞支持一下,还可以收藏起来以备不时之需,有疑问和错误欢迎在评论区指出~
Java||Springboot读取本地目录的文件和文件结构,读取服务器文档目录数据供前端渲染的API实现
|
8月前
|
缓存 Java 应用服务中间件
微服务——SpringBoot使用归纳——Spring Boot集成Thymeleaf模板引擎——依赖导入和Thymeleaf相关配置
在Spring Boot中使用Thymeleaf模板,需引入依赖`spring-boot-starter-thymeleaf`,并在HTML页面标签中声明`xmlns:th=&quot;http://www.thymeleaf.org&quot;`。此外,Thymeleaf默认开启页面缓存,开发时建议关闭缓存以实时查看更新效果,配置方式为`spring.thymeleaf.cache: false`。这可避免因缓存导致页面未及时刷新的问题。
352 0
|
Java 应用服务中间件
SpringBoot获取项目文件的绝对路径和相对路径
SpringBoot获取项目文件的绝对路径和相对路径
665 1
SpringBoot获取项目文件的绝对路径和相对路径
|
XML Java Kotlin
springboot + minio + kkfile实现文件预览
本文介绍了如何在容器中安装和启动kkfileviewer,并通过Spring Boot集成MinIO实现文件上传与预览功能。首先,通过下载kkfileviewer源码并构建Docker镜像来部署文件预览服务。接着,在Spring Boot项目中添加MinIO依赖,配置MinIO客户端,并实现文件上传与获取预览链接的接口。最后,通过测试验证文件上传和预览功能的正确性。
1206 4
springboot + minio + kkfile实现文件预览
|
网络协议 Java
springboot配置hosts文件
springboot配置hosts文件
195 11
|
Java BI API
spring boot 整合 itextpdf 导出 PDF,写入大文本,写入HTML代码,分析当下导出PDF的几个工具
这篇文章介绍了如何在Spring Boot项目中整合iTextPDF库来导出PDF文件,包括写入大文本和HTML代码,并分析了几种常用的Java PDF导出工具。
3027 0
spring boot 整合 itextpdf 导出 PDF,写入大文本,写入HTML代码,分析当下导出PDF的几个工具
|
Java Maven Android开发
eclipse如何导入springboot项目
本文介绍了如何在Eclipse中导入Spring Boot项目。
448 1
eclipse如何导入springboot项目