public void exportCSVFile( HttpServletResponse response, ResultSet rs,String fileName,String headers) throws SQLException { OutputStream o = null; try { // String headers = "用户名, 操作时间, 操作模块, 操作内容";// 标题 headers += " "; List<Log> logList = new ArrayList<Log>(); Log logs = null; while (rs.next()) { logs = new Log(); logs.setUser(rs.getString(1)); logs.setDatetime(rs.getString(2)); logs.setModule(rs.getString(3)); logs.setContent(rs.getString(4)); logList.add(logs); } if (logList.size() > 0) { for (int i = 0; i < logList.size(); i++) { Log logs1 = logList.get(i); headers += logs1.getUser() + ","; headers += logs1.getDatetime() + ","; headers += logs1.getModule() + ","; headers += logs1.getContent(); headers += " "; } Date d = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss"); String dateNowStr = sdf.format(d); // String fileNames = "导出操作日志数据" + dateNowStr+".csv"; String fileNames = fileName + dateNowStr+".csv"; System.out.println(fileNames); response.setContentType("application/download;charset=GBK"); response.setContentType("Content-type:application/vnd.ms-excel;charset=GBK"); response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileNames.getBytes("utf-8"), "iso8859-1"));// 设置头信息 o = response.getOutputStream(); o.write(headers.toString().getBytes("GBK")); } } catch (IOException e) { e.printStackTrace(); } finally { if (o != null) { try { o.close(); } catch (IOException e) { // TODO Auto-generatedcatch block e.printStackTrace(); } } } }
String headers = "用户名, 操作时间, 操作模块, 操作内容";// 标题
String fileName = "导出操作日志数据";
exportCSVFile(response, rs, fileName, headers);
----------------------------------------------
前几天,做的导出csv文件,有个bug,如果服,务器是linux,部署到服务器上就不能导出,后来查出,是导出到了服务器,没有下载到浏览器,
用这个方法,要注意,字节流和字符流的冲突问题;
response.getOutputStream();
PrintWriter out = response.getWriter();
可以将提示写在前台;只用字节流