Java - Writing strings to a CSV file

JavaExcelCsvExport to-Csv

Java Problem Overview


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 Solutions


Solution 1 - Java

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("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());
    }

  }
}

Solution 2 - Java

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!");
	}
}

Solution 3 - Java

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) {
			e.printStackTrace();
		}
		System.out.println("End.");
	}
}

Solution 4 - Java

 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();
        }
    }

Solution 5 - Java

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();
	}
}

Solution 6 - Java

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();

Solution 7 - Java

Generate CSV file from List of Objects
Finally, following is an example showing how to generate a CSV file from List of objects. The example uses the MyUser class defined in the previous section -

import com.opencsv.CSVWriter;
import com.opencsv.bean.StatefulBeanToCsv;
import com.opencsv.bean.StatefulBeanToCsvBuilder;
import com.opencsv.exceptions.CsvDataTypeMismatchException;
import com.opencsv.exceptions.CsvRequiredFieldEmptyException;

import java.io.IOException;
import java.io.Writer;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

public class OpenCSVWriter {
    private static final String STRING_ARRAY_SAMPLE = "./example.csv";

    public static void main(String[] args) throws IOException,
            CsvDataTypeMismatchException,
            CsvRequiredFieldEmptyException {

        try ( Writer writer = Files.newBufferedWriter(Paths.get(STRING_ARRAY_SAMPLE));
        ) {
            StatefulBeanToCsv<MyUser> beanToCsv = new StatefulBeanToCsvBuilder(writer)
                    .withQuotechar(CSVWriter.NO_QUOTE_CHARACTER)
                    .build();

            List<MyUser> myUsers = new ArrayList<>();
            myUsers.add(new MyUser("Sundar Pichai ♥", "[email protected]", "+1-1111111111", "India"));
            myUsers.add(new MyUser("Satya Nadella", "[email protected]", "+1-`enter code here`1111111112", "India"));

            beanToCsv.write(myUsers);
        }
    }
}

Solution 8 - Java

    String filepath="/tmp/employee.csv";
    FileWriter sw = new FileWriter(new File(filepath));
	CSVWriter writer = new CSVWriter(sw);
	writer.writeAll(allRows);
	
	String[] header= new String[]{"ErrorMessage"};
    writer.writeNext(header);

    List<String[]> errorData = new ArrayList<String[]>();
    for(int i=0;i<1;i++){
        String[] data = new String[]{"ErrorMessage"+i};
        errorData.add(data);
    }
    writer.writeAll(errorData);
	
	writer.close();

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionShawView Question on Stackoverflow
Solution 1 - JavaPrashant GView Answer on Stackoverflow
Solution 2 - JavaTamil veera CholanView Answer on Stackoverflow
Solution 3 - JavaSamim AktarView Answer on Stackoverflow
Solution 4 - Javaanil084View Answer on Stackoverflow
Solution 5 - JavaGabriel ArghireView Answer on Stackoverflow
Solution 6 - JavaErnst BlignautView Answer on Stackoverflow
Solution 7 - JavaDanny EscalanteView Answer on Stackoverflow
Solution 8 - JavaSomuchandraView Answer on Stackoverflow