Java - Writing strings to a CSV file
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.
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("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());
}
}
}
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!");
}
}
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.");
}
}