Showing posts with label 亂碼. Show all posts
Showing posts with label 亂碼. Show all posts

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

Monday, March 26, 2012

request.getparameter returns corrupted characters

When inputs non-unicode characters (such as Japanese, Traditional Chinese),  system may returns corrupted characters during request.getParameter("XXX")

It is because the tomcat uses ISO-8859-1 as the default encoding...

Solutions:
1. By declaring page directive
<%@ page contentType="text/html;charset=UTF-8"%>

OR
2. Set the encoding before calling request.getParameter("XXX") in the page
<% 
request.setCharacterEncoding("UTF-8"); 
request.getParameter("XXX");
request.getParameter("YYY");
%>