先贴代码吧,如下:
/*
* 导出文件(excel)
*/
@RequestMapping("test")
public void test(HttpServletRequest request,HttpServletResponse response) {
log.info("--stat_global");
try {
response.setContentType("application/vnd.ms-excel");
request.setCharacterEncoding("UTF-8");
String starttime =getStrParam("starttime",request);
String endtime =getStrParam("endtime",request);
String [] all=request.getParameterValues("selected");
String[] total=request.getParameterValues("total");
String sumtime =starttime+"至"+endtime;
String fileName= sumtime+"全局数据.xls";
String title =("时间 人物 地点 事件");
StringBuffer sbtotal = new StringBuffer();
StringBuffer sb = new StringBuffer();
StringBuffer sbsum = new StringBuffer();
if(total!=null){
sbtotal.append(total[0]);
}
for (int i = 0; i < all.length; i++) {
sb.append(all[i]+"\n");
}
sbsum.append(title+"\n"+sbtotal+"\n"+sb);
response.reset();
byte[] buf = sbsum.toString().getBytes();
// 设置response的Header
response.addHeader("Content-Disposition", "attachment;filename="+new String(fileName.getBytes("gbk"),"iso-8859-1")); //转码之后下载的文件不会出现中文乱码
response.addHeader("Content-Length", "" + buf.length);
try{
//以流的形式下载文件
OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
toClient.write(buf);
toClient.flush();
toClient.close();
}catch(Exception e){
e.printStackTrace();
}
} catch (Exception e) {
// TODO: handle exception
log.error("--testexc, ", e);
e.printStackTrace();
}
}
我是从页面的table中用隐藏域拿了值,然后传过来在写进去,现在实际是文本格式文件,文件名不会出现乱码,而且用WPS打开也不会出现乱码,但是用到微软的offic打开,则里面内容会出现乱码情况,这怎么解决呀?小弟求帮忙,页面用的velocity.
------解决方案--------------------
如果office打开文件出现乱码的话,估计是你文件内容的问题。我没有看到你输出的时候对文本字符串做处理,也就是说你输出的文字是unicode的,这样的话,是会出现乱码的。建议你以GBK编码写入到文件中,具体方法如下:
将这一句
byte[] buf = sbsum.toString().getBytes();
改为
byte[] buf = sbsum.toString().getBytes(“GBK”);
试一下,应该可以