1. 程式人生 > 實用技巧 >java寫入csv檔案

java寫入csv檔案

java換行寫入csv檔案,最後一行去掉空白行

public void Csvcreate(HttpServletRequest request, HttpServletResponse response, List<Map> list) {
        String cateid = "";
        List<String> datalist = new ArrayList();
        for (int i = 0; i < list.size(); i++) {
            Map map = list.get(i);
            StringBuffer sb = new StringBuffer();
            cateid = String.valueOf(map.get("CATEID"));
            sb.append(map.get("CATEID"));
            sb.append(",");
            sb.append(map.get("CARD_NO"));
            //最後一行加上\r\n會出現空白行
            if(i < list.size() - 1){
                sb.append("\r\n");
            }
            datalist.add(sb.toString());
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String todayFile = sdf.format(new Date());
        //目錄
        String path = request.getSession().getServletContext().getRealPath(File.separator) + todayFile + "/";
        log.debug("-------csv----" + path);
        String filename = todayFile;
        File file = new File(path);
        if (!file.isDirectory()) {
            file.mkdirs();
        }
        try {
            //緩衝FileWriter
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(path +
                    "stock_" + cateid + "_" + filename + ".csv")), "GBK"));
            String header = "cateid,卡號\r\n";
            bw.write(header);
            // 新增新的資料行
            for (String str : datalist) {
                bw.write(str);
                bw.flush();
            }
            bw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        File csvFile = new File(path + "stock_" + cateid + "_" + filename + ".csv");
        // 配置檔案下載
        response.setHeader("content-type", "application/octet-stream");
        response.setContentType("application/octet-strea");
        // 實現檔案下載
        byte[] buffer = new byte[1024];
        FileInputStream fis = null;
        BufferedInputStream bis = null;
        try {
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("stock_" + cateid + "_" + filename + ".csv", "UTF-8"));
            fis = new FileInputStream(csvFile);
            bis = new BufferedInputStream(fis);
            OutputStream os = response.getOutputStream();
            int i = bis.read(buffer);
            while (i != -1) {
                os.write(buffer, 0, i);
                i = bis.read(buffer);
            }
            log.info("Download successfully!");
        } catch (Exception e) {
            log.info("Download failed!{}", e);
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }