Java Web读取/输出csv文件

2021-02-25  本文已影响0人  二枚目

简单实现
1、页面上传csv解析成数组;
2、后台字符串生成csv文件并在页面输出下载。

IDEA新建的SpringBoot Demo project
html页面:

    <form action="/file/uploadFile" method="post" enctype="multipart/form-data">
        <input type="file" id="file" name="file" accept=".csv">
        <input type="submit" value="上传" />
    </form>
    <br><br>
    <form action="/file/downloadFile" method="post">
        <input type="submit" value="下载" />
    </form>

控制器

package com.example.demo.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("/file")
public class FileController {

    /**
     * 导入csv文件
     * @param file
     * @param request
     * @param response
     * @throws UnsupportedEncodingException
     */
    @RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
    public void uploadFile(@RequestParam("file") MultipartFile file, HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
        request.setCharacterEncoding("gb2312");
        if (file.isEmpty()) {
            System.out.println("文件为空");
            return;
        }
        InputStreamReader isr = null;
        BufferedReader br = null;
        try {
            isr = new InputStreamReader(file.getInputStream(), "gb2312");
            br = new BufferedReader(isr);
            String line = null;
            List<List<String>> list = new ArrayList<>();
            while ((line = br.readLine()) != null) {
                list.add(Arrays.asList(line.split(",")));
            }
            // list即为所得,用于业务操作、数据持久保存等
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        finally {
            try {
                if (br != null) {
                    br.close();
                }
                if (isr != null) {
                    isr.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 导出csv文件
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping(value = "/downloadFile", method = RequestMethod.POST)
    public void downloadFile(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("application/x-download");
        response.addHeader("Content-Disposition", "attachment;filename="+new String( "导出文件名".getBytes("utf-8"), "ISO8859-1" )+".csv");
        OutputStream out = response.getOutputStream();

        // 模拟生成字符串,一般是后台查询sql结果集拼接而成
        String csvFile = "\"客户姓名\",\"客户类型\",\"联系方式\"\n\"张三\",\"对私\",\"13055874405\t\"\n\"XX集团\",\"对公\",\"0591-8857448\t\"";
        // 向out中写入流
        out.write((csvFile).toString().getBytes("gb2312"));
        out.flush();
        response.flushBuffer();
    }

}

备注:生成csv文件若要为文本格式需在每个数据后面加\t转义符;
出入参的编码根据实际情况转换(用GB2312编码或可避免中文缺失或乱码问题);

上一篇下一篇

猜你喜欢

热点阅读