1.文件名乱码处理
// excel文件名 String fileName="我报表";
final SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHH24mmssSSS"); final String formatStr = formatter.format(new Date()); fileName = fileName + formatStr + "." + fileType; System.out.println(fileName); final HSSFWorkbook wb = createHSSFWorkbook(map); // try {// for testing,created the file in server in path "/home/ap/user/domins/user" // final FileOutputStream xlsStream = new FileOutputStream(fileName); // wb.write(xlsStream); // xlsStream.flush(); // xlsStream.close(); // } catch (final Exception e) { // e.printStackTrace(); // } // 响应到客户端 try { // 解决文件乱码 final String userAgent = request.getHeader("user-agent"); if (userAgent != null && userAgent.indexOf("Firefox") >= 0 || userAgent.indexOf("Chrome") >= 0 || userAgent.indexOf("Safari") >= 0) { fileName = new String(fileName.getBytes(), "ISO8859-1"); } else { fileName = URLEncoder.encode(fileName, "UTF8"); // 其他浏览器 } // setResponseHeader(response, fileName); response.reset();// 清除首部的空白行 response.setCharacterEncoding("UTF-8"); response.setContentType("application/vnd.ms-excel;charset=UTF-8"); response.setHeader("Content-Disposition", "attachment;filename=" + fileName); // response.setHeader("Content-Disposition", "inline;filename=" + fileName); response.addHeader("Pargam", "no-cache"); response.addHeader("Cache-Control", "no-cache"); response.setDateHeader("Expires", 0); response.flushBuffer(); final OutputStream os = response.getOutputStream(); // os.write(wb.getBytes()); wb.write(os); os.flush(); os.close(); } catch (final Exception e) { e.printStackTrace(); } }
2.内容乱码:
tempContent = new String(tempContent.getBytes("UTF-8"), "ISO-8859-1"); // System.out.println(tempContent); tempContent = new String(tempContent.getBytes("ISO-8859-1"), "UTF-8");
cell.setCellValue(tempContent);
3.download.jsp中编码
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ page import="java.sql.*" %> <%@ page import="com.userpackage.*" %> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; request. setCharacterEncoding("UTF-8"); //response.setHeader("Content-Type", "charset=UTF-8"); %> <% out.clear(); out = pageContext.pushBody(); ExcelExport.export(request,response); %>