Home  >  Article  >  Java  >  How to solve the problem of garbled characters in exported csv files using Java

How to solve the problem of garbled characters in exported csv files using Java

尚
Original
2019-12-28 16:29:512445browse

How to solve the problem of garbled characters in exported csv files using Java

When the queried data is exported as an xls file (UTF-8 encoding), the data is normal; but when exported as a CSV file, the Chinese garbled characters in the file are also UTF-8 encoded. , when the export is changed to GBK encoding, the Chinese display is normal. (Recommended: java video tutorial)

Solution:

The file exported in CSV mode does not contain BOM information by default. By giving the content to be output Setting the BOM identifier (byte stream starting with EF BB BF) can solve this problem. The specific method is as follows:

...
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(response.getOutputStream(), "UTF-8");  
// 要输出的内容  
result = (String)contentMap.get(RESPONSE_RESULT);  
response.setHeader("Content-Disposition", "attachment;filename=test.csv");  
outputStreamWriter.write(new String(new byte[]{(byte) 0xEF, (byte) 0xBB, (byte) 0xBF}));  
outputStreamWriter.write(result);  
outputStreamWriter.flush();

If it is implemented with OutputStream stream, the parameters can be modified as follows:

out = response.getOutputStream();     
//加上UTF-8文件的标识字符      
out.write(new byte []{(byte) 0xEF, (byte) 0xBB, (byte) 0xBF});

For more java knowledge, please pay attention to java basic tutorial Column.

The above is the detailed content of How to solve the problem of garbled characters in exported csv files using Java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn