CSV file with “ID” as first item is corrupt in Excel

It’s because MS Excel can’t decide how to open the file with such content.

To solve the issue, replace "ID" with "id".

When you have ID as the first word in a SpreadSheet type file, it matches the specification of a SYLK file and MS Excel (and potentially other SpreadSheet Apps) attempts to open as a SYLK file. However, 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.

id Name
1 Jon Doe
2 Jane Doe

As a bonus, trying to minimize file access by using file object less.

I tested and the code below should work.

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("Jon Doe");
      sb.append('\n');

      sb.append("2");
      sb.append(',');
      sb.append("Jane Doe");
      sb.append('\n');

      writer.write(sb.toString());

      System.out.println("write success.");

    } catch (FileNotFoundException e) {
      System.out.println(e.getMessage());
    }

  }
}

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)