Java - Writing strings to a CSV file

前端 未结 7 2308
野趣味
野趣味 2020-11-28 10:45

I am trying to write data to a csv file with java, however when I try opening the produced file with excel I am getting an error saying the file is corrupt. Upon opening the

7条回答
  •  没有蜡笔的小新
    2020-11-28 11:24

     private static final String FILE_HEADER ="meter_Number,latestDate";
        private static final String COMMA_DELIMITER = ",";
        private static final String NEW_LINE_SEPARATOR = "\n";
        static SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:m m:ss");
    
        private void writeToCsv(Map meterMap) {
            try {
                Iterator> iter = meterMap.entrySet().iterator();
                FileWriter fw = new FileWriter("smaple.csv");
                fw.append(FILE_HEADER.toString());
                fw.append(NEW_LINE_SEPARATOR);
                while (iter.hasNext()) {
                    Map.Entry entry = iter.next();
                    try {
                        fw.append(entry.getKey());
                        fw.append(COMMA_DELIMITER);
                        fw.append(formatter.format(entry.getValue()));
                        fw.append(NEW_LINE_SEPARATOR);
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        iter.remove();
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    

提交回复
热议问题