Java - Writing strings to a CSV file

前端 未结 7 2137
野趣味
野趣味 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:23

    Answer for this question is good if you want to overwrite your file everytime you rerun your program, but if you want your records to not be lost at rerunning your program, you may want to try this

    public void writeAudit(String actionName) {
        String whereWrite = "./csvFiles/audit.csv";
    
        try {
            FileWriter fw = new FileWriter(whereWrite, true);
            BufferedWriter bw = new BufferedWriter(fw);
            PrintWriter pw = new PrintWriter(bw);
    
            Date date = new Date();
    
            pw.println(actionName + "," + date.toString());
            pw.flush();
            pw.close();
    
        } catch (FileNotFoundException e) {
            System.out.println(e.getMessage());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    0 讨论(0)
  • 2020-11-28 11:23

    I see you already have a answer but here is another answer, maybe even faster A simple class to pass in a List of objects and retrieve either a csv or excel or password protected zip csv or excel. https://github.com/ernst223/spread-sheet-exporter

    SpreadSheetExporter spreadSheetExporter = new SpreadSheetExporter(List<Object>, "Filename");
    File fileCSV = spreadSheetExporter.getCSV();
    
    0 讨论(0)
  • 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<String, Date> meterMap) {
            try {
                Iterator<Map.Entry<String, Date>> 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<String, Date> 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();
            }
        }
    
    0 讨论(0)
  • 2020-11-28 11:29

    I think this is a simple code in java which will show the string value in CSV after compile this code.

    public class CsvWriter {
    
        public static void main(String args[]) {
            // File input path
            System.out.println("Starting....");
            File file = new File("/home/Desktop/test/output.csv");
            try {
                FileWriter output = new FileWriter(file);
                CSVWriter write = new CSVWriter(output);
    
                // Header column value
                String[] header = { "ID", "Name", "Address", "Phone Number" };
                write.writeNext(header);
                // Value
                String[] data1 = { "1", "First Name", "Address1", "12345" };
                write.writeNext(data1);
                String[] data2 = { "2", "Second Name", "Address2", "123456" };
                write.writeNext(data2);
                String[] data3 = { "3", "Third Name", "Address3", "1234567" };
                write.writeNext(data3);
                write.close();
            } catch (Exception e) {
                // TODO: handle exception
                e.printStackTrace();
    
            }
    
            System.out.println("End.");
    
        }
    }
    
    0 讨论(0)
  • 2020-11-28 11:34

    Basically it's because MS Excel can't decide how to open the file with such content.

    When you put ID as the first character in a Spreadsheet type file, it matches the specification of a SYLK file and MS Excel (and potentially other Spreadsheet Apps) try to open it as a SYLK file. But at the same time, it does not meet the complete specification of a SYLK file since rest of the values in the file are comma separated. Hence, the error is shown.

    To solve the issue, change "ID" to "id" and it should work as expected.

    enter image description here

    This is weird. But, yeah!

    Also trying to minimize file access by using file object less.

    I tested and the code below works perfect.

    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.PrintWriter;
    
    public class CsvWriter {
      public static void main(String[] args) {
    
        try (PrintWriter writer = new PrintWriter(new File("test.csv"))) {
    
          StringBuilder sb = new StringBuilder();
          sb.append("id,");
          sb.append(',');
          sb.append("Name");
          sb.append('\n');
    
          sb.append("1");
          sb.append(',');
          sb.append("Prashant Ghimire");
          sb.append('\n');
    
          writer.write(sb.toString());
    
          System.out.println("done!");
    
        } catch (FileNotFoundException e) {
          System.out.println(e.getMessage());
        }
    
      }
    }
    
    0 讨论(0)
  • 2020-11-28 11:37
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.PrintWriter;
    
    public class CsvFile {
    
        public static void main(String[]args){
            PrintWriter pw = null;
            try {
                pw = new PrintWriter(new File("NewData.csv"));
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            StringBuilder builder = new StringBuilder();
            String columnNamesList = "Id,Name";
            // No need give the headers Like: id, Name on builder.append
            builder.append(columnNamesList +"\n");
            builder.append("1"+",");
            builder.append("Chola");
            builder.append('\n');
            pw.write(builder.toString());
            pw.close();
            System.out.println("done!");
        }
    }
    
    0 讨论(0)
提交回复
热议问题