java 导入、导出 csv

1.在pom.xml文件中加

         <dependency>
             <groupId>commons-io</groupId>
             <artifactId>commons-io</artifactId>
             <version>2.4</version>
         </dependency>

2.在application.yml文件中加

    servlet: 
        multipart:
            # MULTIPART (MultipartProperties)
            enabled: true 
            # multipart.location指定上传文件存放的目录.当我们指定了location后,我们在调用Part的write(String fileName)方法把文件写入到硬盘的时候可以,文件名称可以不用带路径,但是如果fileName带了绝对路径,那将以fileName所带路径为准把文件写入磁盘
            file-size-threshold: 0B
            # max-file-size:数值类型,表示单个文件的最大大小.默认为-1,表示不限制.当有单个文件的大小超过了max-file-size指定的值时将抛出IllegalStateException异常
            max-file-size: 102400MB
            # max-request-size:数值类型,表示一次上传文件的最大大小.默认为-1,表示不限制.当上传时所有文件的大小超过了max-request-size时也将抛出IllegalStateException异常.
            max-request-size: 102400MB

3.建立工具类CSVUtils

public class CSVUtils {
/* 导出
 * 
 * @param file csv文件(路径+文件名),csv文件不存在会自动创建
 * @param dataList 数据
 * @return
 */
 public static boolean exportCsv(File file, List<String> dataList){
    boolean isSucess=false; 
    FileOutputStream out=null;
    OutputStreamWriter osw=null;
    BufferedWriter bw=null;
    try {
        //  OutputStreamWriter in_=new OutputStreamWriter(new FileOutputStream("文件名"), "gbk");
        out = new FileOutputStream(file);
        osw = new OutputStreamWriter(out, "gbk");
        bw =new BufferedWriter(osw);
        if(dataList!=null && !dataList.isEmpty()){
            for(String data : dataList){
             bw.append(data).append("\r");
            }
        }
        isSucess=true;
    } catch (Exception e) {
        isSucess=false;
    }finally{
        if(bw!=null){
            try {
                bw.close();
                bw=null;
            } catch (IOException e) {
                e.printStackTrace();
            } 
        }
        if(osw!=null){
            try {
                osw.close();
                osw=null;
            } catch (IOException e) {
                e.printStackTrace();
            } 
        }
        if(out!=null){
            try {
                out.close();
                out=null;
            } catch (IOException e) {
                e.printStackTrace();
            } 
        }
    }
  
    return isSucess;
 }
  
 /**
 * 导入
 * 
 * @param file csv文件(路径+文件)
 * @return
 */
 public static List<String> importCsv(File file){
    List<String> dataList=new ArrayList<String>(); 
    BufferedReader br=null;
    try { 
        br = new BufferedReader(new FileReader(file));
        String line = ""; 
        while ((line = br.readLine()) != null) { 
        dataList.add(line);
        }
    }catch (Exception e) {
    }finally{
        if(br!=null){
            try {
                br.close();
                br=null;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    return dataList;
    } 
 
 /**

*  删除文件夹里面的所有文件

*  @param  path  String  文件夹路径  如  c:/fqf

*/

    public static void  delAllFile(String  path)  {
        File  file  =  new  File(path);

        if  (!file.exists())  {
            return; 
        }

        if  (!file.isDirectory())  {
            return; 
        }

        String[]  tempList  =  file.list();

        File  temp  =  null;

        for  (int  i  =  0;  i  <  tempList.length;  i++)  {
        if  (path.endsWith(File.separator))  {
        temp  =  new  File(path  +  tempList[i]); 
        }

        else  {
        temp  =  new  File(path  +  File.separator  +  tempList[i]); 
        }

        if  (temp.isFile())  {
        temp.delete(); 
        }

        if  (temp.isDirectory())  {
        //先删除文件夹里面的文件

        delAllFile(path+"/"+  tempList[i]);

        /*//再删除空文件夹

        delFolder(path+"/"+  tempList[i]);*/

        }

        }

    }
}

4. 接口 Contorller

    @PostMapping("/exportLine")
    @ApiOperation("导出线路")
    public String exportLine(
           // @RequestParam(value = "id") String id,
            HttpServletRequest request, 
            HttpServletResponse response
    ) throws Exception {
        List<String> dataList =new ArrayList(); 
        dataList=lineService.exportLine();
        response.setCharacterEncoding("GBK");
        SimpleDateFormat dfs = new SimpleDateFormat("yyyyMMddHHmmss");// 设置日期格式
        Date time = new Date();
        String tStamp = dfs.format(time);
        String filename = "IpMacPortExport"+tStamp + ".csv";
        response.setHeader("contentType", "text/html; charset=GBK");
        response.setContentType("application/octet-stream");
        response.addHeader("Content-Disposition", "attachment; filename="+filename);
        String cp=request.getSession().getServletContext().getRealPath("/");
        String path = cp+"\\"+filename;
        File file = new File(path);
        BufferedInputStream bis = null;
        BufferedOutputStream out = null;
        FileWriterWithEncoding fwwe =new FileWriterWithEncoding(file,"GBK");
        BufferedWriter bw = new BufferedWriter(fwwe);
        if(dataList!=null && !dataList.isEmpty()){
            for(String data : dataList){
                bw.write(data);
                bw.write("\n");
            }
        }
        bw.close();
        fwwe.close();
        try {
            bis = new BufferedInputStream(new FileInputStream(file));
            out = new BufferedOutputStream(response.getOutputStream());
            byte[] buff = new byte[2048];
            while (true) {
                int bytesRead;
                if (-1 == (bytesRead = bis.read(buff, 0, buff.length))){
                    break;
                }
                out.write(buff, 0, bytesRead);
            }
            file.deleteOnExit();
        }
        catch (IOException e) {
            throw e;
        }
        finally{
            try {
                if(bis != null){
                    bis.close();
                }
                if(out != null){
                    out.flush();
                    out.close();
                }
            }
            catch (IOException e) {
                throw e;
            }
        }
        //delAllFile(cp+"download/");
        return null;

    } 
    
    
    
    @PostMapping("/importLine")
    @ApiOperation("导入线路")
    public JSONObject importLine( HttpServletRequest request, 
                            @RequestParam(value = "file") MultipartFile[] buildInfo )
    throws ServletException, IOException {
        JSONObject result = new JSONObject();
        // 得到上传文件的保存目录,将上传的文件存放于WEB-INF目录下,不允许外界直接访问,保证上传文件的安全
        //String savePath = request.getSession().getServletContext().getRealPath("/WEB-INF/upload");
        String savePath = System.getProperty("user.dir").replaceAll("\\\\", "/")+"/upload/";
        savePath = savePath.replace("file:", ""); // 去掉file:
        File file1 = new File(savePath);
        // 判断上传文件的保存目录是否存在
        if (!file1.exists() && !file1.isDirectory()) {
        log.info(savePath + "目录不存在,需要创建");
        file1.mkdir();
        }
        // 删除此路径下的所有文件以及文件夹
        CSVUtils.delAllFile(savePath);
        String str="";
        try {
            InputStream is = buildInfo[0].getInputStream();// 多文件也适用,我这里就一个文件
            byte[] b = new byte[(int) buildInfo[0].getSize()];
            int read = 0;
            int i = 0;
            while ((read = is.read()) != -1) {
            b[i] = (byte) read;
            i++;
            }
            is.close();
            String filePath = savePath  + "temp" + "_" + buildInfo[0].getOriginalFilename();
            log.info("临时文件保存路径:" + savePath + "temp" + "_" + buildInfo[0].getOriginalFilename());
            OutputStream os = new FileOutputStream(new File(savePath + "temp" + "_" + buildInfo[0].getOriginalFilename()));// 文件原名,如a.txt
            os.write(b);
            os.flush();
            os.close();
            result =lineService.importLine(filePath);  
        } catch (Exception ex) {
            result.put("code", MsgObj.fail.getCode());
            result.put("msg", MsgObj.fail.getMsg());
            result.put("data", ex.getMessage());
        }
            return result; 
    }

5.逻辑层Service

    /**
     * 6.导出线路 
     */
    public List<String> exportLine() throws Exception {
        List<String> dataList = new ArrayList<String>();
        try {
        //List<String> ids =Arrays.asList(id.split(","));
        List<Line> list = lineDao.findAll(Sort.by(Sort.Direction.DESC, "createTime"));
        dataList.add("线路长度,所在省区,启用状态,线路名称,说明,创建时间,修改时间,删除标记");
        for (int i = 0; i < list.size(); i++) { 
        dataList.add("\""+list.get(i).getLineLength()+"\",\"" 
                + list.get(i).getProvincesCity()+"\",\"" 
                + list.get(i).getEnabled()+"\",\"" 
                + list.get(i).getLineName()+"\",\"" 
                + list.get(i).getDescription()+"\",\"" 
                + DateUtil.format(list.get(i).getCreateTime(), "yyyy-MM-dd HH:mm")  +"\",\"" 
                + DateUtil.format(list.get(i).getUpdateTime(), "yyyy-MM-dd HH:mm")+"\",\"" 
                + list.get(i).getDel()+"\"" ); 
        }
        } catch (Exception e) {
        e.printStackTrace();
        }
        return dataList;
     } 
    
    /**
     * 7.导入线路 
     */
    public JSONObject importLine(String filePath) throws Exception {
        JSONObject result = new JSONObject(); 
        List<String> dataList = CSVUtils.importCsv(new File(filePath));
        try{
            if (dataList != null && !dataList.isEmpty()) {
                List list=new ArrayList();
                for (int i = 1; i < dataList.size(); i++) {
                    String data = dataList.get(i);
                    String[] source = data.trim().split(",(?=([^\\\"]*\\\"[^\\\"]*\\\")*[^\\\"]*$)",-1);
                    if (source[0] != "") { 
                        Line  base= new Line();
                        base.setLineLength(source[0].replaceAll("\\\"", ""));
                        base.setProvincesCity(source[1].replaceAll("\\\"", ""));
                        base.setEnabled(Integer.parseInt(source[2].replaceAll("\\\"", "")));
                        base.setLineName(source[3].replaceAll("\\\"", ""));
                        base.setDescription(source[4].replaceAll("\\\"", ""));
                        base.setCreateTime(DateUtil.parse(source[5].replaceAll("\\\"", ""), "yyyy-MM-dd HH:mm"));
                        base.setUpdateTime(DateUtil.parse(source[6].replaceAll("\\\"", ""), "yyyy-MM-dd HH:mm"));
                        base.setDel(Integer.parseInt(source[7].replaceAll("\\\"", ""))); 
                        list.add(base);
                        Line line = lineDao.findOne(Criteria.where("lineName").is(source[3].replaceAll("\\\"", "")));
                        if (line != null) {//存在
                            result.put("code", MsgObj.is_exist.getCode());
                            result.put("msg", MsgObj.is_exist.getMsg());
                            return result;
                        }
                    } 
                }
                lineDao.saveAll(list);
            }
            result.put("code", MsgObj.success.getCode());
            result.put("msg", MsgObj.success.getMsg());
        } catch (Exception ex) {
            result.put("code", MsgObj.fail.getCode());
            result.put("msg", MsgObj.fail.getMsg());
            result.put("data", ex.getMessage());
        }
        return result;
    }

  • 2
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值