Thursday, April 12, 2012

[Resolved] Download CSV with UTF-8 handling

System generates garbage characters or question marks ??? when exporting a CSV file with Chinese character, Japanese Character..



It is okay to view the Chinese / Japanese character in notepad, but cannot be shown correctly in Excel.
It is because Excel does not handle the unicode well.


Solution
It can be solved by adding addition header (BOM, Byte order Mask) to the downloaded CSV file.

response.setContentType("application/vnd.ms-excel:UTF-8");
response.setHeader("Content-Disposition", "attachment; filename=myOutputFile.csv");

// Excel does not recongize the UTF-8, add additional header (BOM) for excel
OutputStream outputStream = response.getOutputStream();
outputStream.write(0xEF);  
outputStream.write(0xBB);
outputStream.write(0xBF);  


BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));

// Your method that generate the CSV content
writeSth(writer);

writer.flush();
writer.close();