servlet导出文件名为中文的excel错误有关问题解决方法
servlet导出文件名为中文的excel异常问题解决办法
项目中遇到将查询结果导出为一个excel文件,当动态生成的文件名为英文时成功生成,文件名为中文的再次导出浏览器就出一些莫名其妙的问题(导出文件不是一个excel),问题处理方法如下:
action中的代码片段:
System.out.println("exportExcel"); String ruleId = request.getParameter("ruleId"); String ruleName = request.getParameter("ruleName"); String ruleType = request.getParameter("ruleType"); String statisticDate = request.getParameter("statisticDate"); String smsCount = request.getParameter("smsCount"); try{ HSSFWorkbook workBook = new HSSFWorkbook(); HSSFSheet sheet = workBook.createSheet(); HSSFRow row0 = sheet.createRow(0); row0.createCell((short)0).setCellValue("规则编号"); row0.createCell((short)1).setCellValue("规则名称"); row0.createCell((short)2).setCellValue("规则类型"); row0.createCell((short)3).setCellValue("发送日期"); row0.createCell((short)4).setCellValue("发送数量"); HSSFRow row1 = sheet.createRow(1); row1.createCell((short)0).setCellValue(ruleId); row1.createCell((short)1).setCellValue(ruleName); row1.createCell((short)2).setCellValue(ruleType); row1.createCell((short)3).setCellValue(statisticDate); row1.createCell((short)4).setCellValue(smsCount); response.reset(); //清空输出流 //response.setHeader("Content-disposition", "attachment; filename=短信自动发送-"+ruleName+"-"+statisticDate+".xls"); String fileName = "短信自动发送-"+ruleName+"-"+statisticDate; response.setHeader("Content-disposition", "attachment; filename="+StringtoUTF8.toUtf8String(fileName)+".xls"); response.setContentType("application/ms-excel;charset=GBK"); ServletOutputStream out = response.getOutputStream(); workBook.write(out); out.flush(); out.close();
处理中文的类:
写道
public class StringtoUTF8 { public static String toUtf8String(String s) { StringBuffer sb = new StringBuffer(); for (int i=0;i<s.length();i++){ char c = s.charAt(i); if (c >= 0 && c <= 255) { sb.append(c); } else { byte[] b; try { b = Character.toString(c).getBytes("utf-8"); } catch (Exception ex) { System.out.println(ex); b = new byte[0]; } for (int j = 0; j < b.length; j++) { int k = b[j]; if (k < 0) k += 256; sb.append("%" + Integer.toHexString(k). toUpperCase()); } } } return sb.toString(); }
经过上面 StringtoUTF8 处理过的中文字符串可以正常导出excel,问题解决。