搜了一下,发现网上都是解决文件名乱码的问题,这里记录一下从数据库查询出的数据写入文件中文乱码的问题
个人采用的是对象查询出来以后转为json字符串,然后字符串进行转码,再转成jsonObject格式
下面贴代码
这个是进行转码的的代码
public static String garbled(HttpServletRequest request, String str) throws UnsupportedEncodingException {
String userAgent = request.getHeader("User-Agent");
byte[] bytes = userAgent.contains("MSIE") ? str.getBytes() : str.getBytes("UTF-8");
str = new String(bytes, "ISO-8859-1");
return str;
}
拿到对象数据后
User user=new User();
user.setUsername("钢铁侠")
jsonStr=JSON.toJSONString(User);
controller层进行转码并且导出
/**
* 这里以json字符串获取,方便进行转码
* 如果直接导出word文档会导致中文乱码
*/
String jsonStr=userService.getData(id);
jsonStr=RequestUtil.garbled(request,jsonStr);
JSONObject jsonObject= JSON.parseObject(jsonStr);
//设置word文件名称
String fileName="xxxx个人信息表"+sdf.format(new Date());
fileName= RequestUtil.garbled(request,fileName);
response.setHeader("Content-Disposition", "attachment;filename="+fileName+".doc");
Configuration configuration = new Configuration();
configuration.setDefaultEncoding("ISO-8859-1");
configuration.setClassForTemplateLoading(this.getClass(), "/templates/");//模板文件所在路径
Template t=null;
try {
t = configuration.getTemplate("mo.ftl"); //获取模板文件
} catch (IOException e) {
e.printStackTrace();
}
Writer out = null;
try {
out = response.getWriter();
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
t.process(jsonObject, out); //将填充数据填入模板文件并输出到目标文件
} catch (TemplateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
这里是导出word举例