前端代碼
<script type="text/javascript">
window.location = '${servePath}/pc/wuye/doExportExcel?type=0';
</script>
特別注意一下這不能使用Ajax進行傳參數(shù)和跳轉(zhuǎn)頁面,因為ajax不提供下載。
后臺代碼
// 在內(nèi)存中創(chuàng)建一個Excel文件,通過輸出流寫到客戶端提供下載 HSSFWorkbook workbook = new HSSFWorkbook(); // 創(chuàng)建一個sheet頁 HSSFSheet sheet = workbook.createSheet("物業(yè)投訴"); // 創(chuàng)建標題行 HSSFRow headRow = sheet.createRow(0); headRow.createCell(0).setCellValue("投訴類型"); headRow.createCell(1).setCellValue("投訴內(nèi)容"); headRow.createCell(2).setCellValue("創(chuàng)建時間"); headRow.createCell(3).setCellValue("創(chuàng)建人"); headRow.createCell(4).setCellValue("更新時間"); headRow.createCell(5).setCellValue("更新人"); SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); for (logistics_complaintsAO complaintsA : orderResult) { HSSFRow dataRow = sheet.createRow(sheet.getLastRowNum() + 1); dataRow.createCell(0).setCellValue(complaintsA.getSecondary_classification()); dataRow.createCell(1).setCellValue(complaintsA.getContent()); dataRow.createCell(2).setCellValue(df.format(complaintsA.getCreate_time())); dataRow.createCell(3).setCellValue(complaintsA.getCreate_by()); dataRow.createCell(4).setCellValue(df.format(complaintsA.getUpdate_time())); dataRow.createCell(4).setCellValue(complaintsA.getUpdate_by()); } String filename = "物業(yè)投訴.xls"; String agent = request.getHeader("User-Agent"); filename = FileUtils.encodeDownloadFilename(filename, agent); //一個流兩個頭 ServletOutputStream out = response.getOutputStream(); String contentType = response.getContentType(); response.setContentType(contentType); response.setHeader("content-disposition", "attchment;filename="+filename); workbook.write(out);
其中使用到一個工具類
public class FileUtils { /** * 下載文件時,針對不同瀏覽器,進行附件名的編碼 * * @param filename * 下載文件名 * @param agent * 客戶端瀏覽器 * @return 編碼后的下載附件名 * @throws IOException */ public static String encodeDownloadFilename(String filename, String agent) throws IOException { if (agent.contains("Firefox")) { // 火狐瀏覽器 filename = "=?UTF-8?B?" + new BASE64Encoder().encode(filename.getBytes("utf-8")) + "?="; filename = filename.replaceAll("/r/n", ""); } else { // IE及其他瀏覽器 filename = URLEncoder.encode(filename, "utf-8"); filename = filename.replace("+"," "); } return filename; }}
新聞熱點
疑難解答