读书人

servlet导出文件名为中文的excel错误有

发布时间: 2012-12-27 10:17:10 作者: rapoo

servlet导出文件名为中文的excel异常问题解决办法

?

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,问题解决。

读书人网 >编程

热点推荐