內容簡介
本文內容使用java實現數據生成CSV文件,有關CSV文件知識請參考:CSV (逗號分隔值文件格式)
實現代碼(僅供參考,請根據實現情況來修改)

/** * 坐標點參數實體類 */ public class PointsParamDto { /** * 坐標id(由1開始,累加1,這樣的:1,2,3,4,5...) */ private String pointId; /** * X 坐標點 */ private String x; /** * X 坐標點 */ private String y; public PointsParamDto(){} public PointsParamDto(String pointId,String x,String y){ this.pointId = pointId; this.x = x; this.y = y; } public String getPointId() { return pointId; } public void setPointId(String pointId) { this.pointId = pointId; } public String getX() { return x; } public void setX(String x) { this.x = x; } public String getY() { return y; } public void setY(String y) { this.y = y; } public String toRow(){ return String.format("%s,%s,%s",this.pointId,this.x,this.y); } }
/** * 生成csv文件 * @param pointsList * @return */ private void PointsToCsvFile(List<PointsParamDto> pointsList){ if (pointsList!=null && pointsList.size() > 0){ // 表格頭 String[] headArr = new String[]{"PointId", "X", "Y"}; //CSV文件路徑及名稱 LocalDateTime localDateTime = LocalDateTime.now(); DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyyMMddHHmmss"); String filePath = "E:\\TestCsvDirectory"; //CSV文件路徑 String fileName = "CSV_"+ df.format(localDateTime) +".csv";//CSV文件名稱 File csvFile = null; BufferedWriter csvWriter = null; try { csvFile = new File(filePath + File.separator + fileName); File parent = csvFile.getParentFile(); if (parent != null && !parent.exists()) { parent.mkdirs(); } csvFile.createNewFile(); // GB2312使正確讀取分隔符"," csvWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(csvFile), "GB2312"), 1024); //這部分在第一行居中展示文件名稱,根據實際情況,可選擇取消注釋 /*int num = headArr.length / 2; StringBuffer buffer = new StringBuffer(); for (int i = 0; i < num; i++) { buffer.append(","); } csvWriter.write(buffer.toString() + fileName + buffer.toString()); csvWriter.newLine();*/ // 寫入文件頭部標題行 csvWriter.write(String.join(",", headArr)); csvWriter.newLine(); // 寫入文件內容 for (PointsParamDto points : pointsList) { csvWriter.write(points.toRow()); csvWriter.newLine(); } csvWriter.flush(); } catch (Exception e) { e.printStackTrace(); } finally { try { csvWriter.close(); } catch (IOException e) { e.printStackTrace(); } } } }
調用
List<PointsParamDto> pointsParamDtos = new ArrayList<>(); pointsParamDtos.add(new PointsParamDto("1","62.05932617","54.60449277")); pointsParamDtos.add(new PointsParamDto("2","62.42138672","54.06616269")); pointsParamDtos.add(new PointsParamDto("3","63.22387695","52.02270566")); pointsParamDtos.add(new PointsParamDto("4","61.32324219","53.60449277")); pointsParamDtos.add(new PointsParamDto("5","62.68603516","54.03320371")); PointsToCsvFile(pointsParamDtos);
結果
生成文件如下圖:
打開效果如下: