/** * 导出excel表格 */ @RequestMapping(value = "/doExportData", method = {RequestMethod.POST, RequestMethod.GET}) public void doExportUserData(HttpServletRequest request, HttpServletResponse response,ModelMap modelMap){ String enddate = (String) request.getParameter("enddate"); //查询数据列表 List<User> userList = aService.findByDate(enddate); // 生成提示信息, response.setContentType("application/vnd.ms-excel"); try{ //拼凑文件名称:时间+随机数 String fileName = "" ; String[] date2 = enddate.split("-"); for(int i=0;i<date2.length;i++){ fileName = fileName+date2[i]; } //方法二: //String fileName = enddate.replace("-", ""); fileName = fileName+Math.round(Math.random()*10000);//添加随机数 response.setHeader("content-disposition", "attachment;filename=" + fileName + ".xls"); // 产生工作簿对象 HSSFWorkbook workbook = new HSSFWorkbook(); //产生工作表对象 HSSFSheet sheet = workbook.createSheet("用户列表"); //设置sheet页名称 HSSFRow row = sheet.createRow(0); HSSFCellStyle style = workbook.createCellStyle(); style.setAlignment(CellStyle.ALIGN_CENTER); // 创建一个居中格式 HSSFCell cell = row.createCell(0); cell.setCellValue("部门名称"); cell.setCellStyle(style); cell = row.createCell(1); cell.setCellValue("工号"); cell.setCellStyle(style); cell = row.createCell(2); cell.setCellValue("姓名"); cell.setCellStyle(style); cell = row.createCell(3); cell.setCellValue("时间"); cell.setCellStyle(style); //循环数据 for (int i = 0; i < userList.size(); i++){ row = sheet.createRow(i + 1); User user = userList.get(i); //创建单元格,并设置值 row.createCell(0).setCellValue(user.getDeptName()); row.createCell(1).setCellValue(user.getUserid()); row.createCell(2).setCellValue(user.getName()); row.createCell(3).setCellValue(enddate); } //文件导出路径,项目中的exportfile文件下 String path = request.getSession().getServletContext() .getRealPath("/"); String filePath =path+"exportfile\\"+fileName+".xls"; OutputStream os = new FileOutputStream(filePath); workbook.write(os); os.close(); //下载文件(只是导出到了相应的文件下面,下载中没有,不添加此方法,在谷歌浏览器中不能直接可以打开文件,提示保存文件名称不一致,打开是空的) File templateFile = new File(filePath); FileUtil.downloadFile(response, templateFile); }catch (Exception e){ e.printStackTrace(); } }
FileUtil.java 下载相关的工具类
import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang3.StringUtils; /** * 文件工具类 */ public class FileUtil { /** * 下载文件 * * @param response * @param file * @throws Exception */ public static void downloadFile(HttpServletResponse response, File file) throws Exception { if (null == response || null == file) return; InputStream is = null; OutputStream os = null; if (file.exists()) { // 2 文件名称 String fileName = getFileNameByCompleteFilePath(file.getName()); // 3 文件大小 String fileLength = String.valueOf(file.length()); // 4 下载文件名称 String realDownLoadFileName = new String(fileName.getBytes(), "8859_1"); // 5 设置响应参数 response.reset(); response.setContentType("application/x-msdownload;"); response.setHeader("Content-disposition", "attachment; filename=" + realDownLoadFileName); response.setHeader("Content-Length", fileLength); response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0"); response.setHeader("Pragma", "public"); response.setDateHeader("Expires", System.currentTimeMillis() + 1000L); try { is = new BufferedInputStream(new FileInputStream(file)); os = new BufferedOutputStream(response.getOutputStream()); byte[] buffer = new byte[1024]; while (true) { int size = is.read(buffer, 0, 1024); if (size == -1) { break; } os.write(buffer, 0, size); } } catch (Exception e) { e.printStackTrace(); } finally { try { if (is != null) { is.close(); } } catch (IOException e) { e.printStackTrace(); } try { if (os != null) { os.close(); } } catch (IOException e) { e.printStackTrace(); } } response.setStatus(HttpServletResponse.SC_OK); try { response.flushBuffer(); } catch (IOException e) { } } else { // System.out.println("下载文件不存在,文件路径: " + file.getAbsolutePath()); // 如果文件不存在,则创建异常对象并向上抛出 throw new Exception(); } } public static String getFileNameByCompleteFilePath(String path) { if (StringUtils.isBlank(path)) return ""; // 1 转化路径为本地串 path = toLocalPath(path); // 2 处理 if (StringUtils.isNotBlank(path)) { int index = path.lastIndexOf(File.separator); return path = path.substring(index + 1); } return ""; } public static final String toLocalPath(String pathString) { if (StringUtils.isBlank(pathString)) return ""; pathString = replace(pathString, "/", File.separator); pathString = replace(pathString, "\\", File.separator); return pathString; } public static final String replace(String line, String oldString, String newString) { // 递归算法 int i = 0; if ((i = line.indexOf(oldString, i)) >= 0) { char[] line2 = line.toCharArray(); char[] newString2 = newString.toCharArray(); int oLength = oldString.length(); StringBuffer buf = new StringBuffer(line2.length); buf.append(line2, 0, i).append(newString2); i += oLength; int j = i; while ((i = line.indexOf(oldString, i)) > 0) { buf.append(line2, j, i - j).append(newString2); i += oLength; j = i; } buf.append(line2, j, line2.length - j); return buf.toString(); } return line; } }
时间: 2024-10-18 16:12:53