天天看點

java 逐行寫入csv_Java - 将字元串寫入CSV檔案

java 逐行寫入csv_Java - 将字元串寫入CSV檔案

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 file in notepad it looks to be formatted correctly so I'm not sure what the issue is. I am using the FileWriter class to output the data to the file.

FileWriter writer = new FileWriter("test.csv");

writer.append("ID");

writer.append(',');

writer.append("name");

writer.append(',');

...

writer.append('\n');

writer.flush();

writer.close();

Do I need to use some library in java in order to print to a csv file? I presumed you could just do this natively in java as long as you used the correct formatting.

Appreciate the help,

Shaw

解決方案

java 逐行寫入csv_Java - 将字元串寫入CSV檔案

According to this Microsoft Documentation, the error is shown because of the uppercase word "ID" as first row. Change it to "id" and it works as expected.

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 CSV {

public static void main(String[]args) throws FileNotFoundException{

PrintWriter pw = 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');

pw.write(sb.toString());

pw.close();

System.out.println("done!");

}

}