HttpServletResponse res = null; res = getResponse(); res.reset(); // res.setContentType("octets/stream"); res.setContentType("application/octet-stream; charset=utf-8"); // res.setContentType("application/vnd.ms-excel;charset=utf-8"); // res.setContentType("application/msexcel"); String fileName = sensorShowNo + "_eff_data_export"; // res.setCharacterEncoding("UTF-8"); // res.addHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("utf-8"), "ISO8859-1") + ".xls"); // res.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName + ".xls","UTF-8")); res.addHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("gb2312"), "ISO8859-1") + ".xls"); // res.addHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("gbk"), "ISO8859-1") + ".xls"); OutputStream out = response.getOutputStream(); Workbook workbook = sensorDataService.exportEff(sensor.getSensorNo(), sensorSearch.getStartTime(), sensorSearch.getEndTime()); workbook.write(res.getOutputStream()); out.flush(); out.close();
OutputStream是字节流,将文本按字节写入文件,而一个汉字是两个字节,无法一次写入,就会出现乱码,解决方法是使用OutputStreamWriter将字节流转换为字符流写入,同时指定utf-8编码.
new OutputStreamWriter(new OutputStream(file), "utf-8"); 你用这个试下