When importing the resulting CSV file into Excel, currency signs other than and $ are replaced by ? . In Notepad ++, everything is displayed normally.

 String data = "$,€,₪,₴,zł,kr,£,..." String fileName = "C:\\Program Files\\Java\\apache-tomcat-7.0.68\\temp\\testCSV.csv"; String uncode = "UTF-8"; //uncode = "UTF-8", "UTF-16", "UTF-16BE", "UTF-16LE", "Cp866", "Cp1251", "US-ASCII", "ISO-8859-1"; 

I tried different options:

  1. FileWriter out = new FileWriter(fileName);

  2. OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(fileName),uncode);

  3. PrintWriter out = new PrintWriter(fileName, uncode));

  4. PrintWriter out = new PrintWriter (new OutputStreamWriter (new FileOutputStream (fileName), uncode));

  5. Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName), uncode));

  6. :

     File f = new File(fileName); FileUtils.writeStringToFile(f, data, uncode); out.append(data); //out.write(data); //out.println(data); 

What could be the problem?

  • How do you view the resulting file? So all the ways, except the first, should work. There may still be a compiler's opinion on the encoding of the source does not match yours - zRrr
  • I open in Microsoft Excel. What is true, if you open in "Notepad + +" then the characters are displayed correctly. - Giovanni
  • Like in Excel, when importing csv, you can select the encoding - zRrr

1 answer 1

I could be wrong, but as far as I remember, MS Excel does not recognize UTF-8 without a BOM (Byte Order Mark), t.ch. try something like this:

 BufferedWriter writer = new BufferedWriter( new OutputStreamWriter(new FileOutputStream("file.txt", true), "utf8")); writer.append('\uFEFF'); writer.append("мама мыла раму"); 

Check

 » /usr/bin/printf "\ufeff...\n" | file file.txt file.txt: UTF-8 Unicode (with BOM) text, with no line terminators 

At the same time, most BOM text editors are not interested, so your text is displayed normally in them.

  • Thank. Adding writer.append('\uFEFF'); . - Giovanni