Java - Writing strings to a CSV file

前端 未结 7 2255
野趣味
野趣味 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: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!");
        }
    }
    

提交回复
热议问题