廢話不說了,開始了!html
方案一:JFinal的renderFile("路徑")功能java
先說說個人邏輯:web
前臺頁面點擊請求發送到後臺Controller,而後Controller層主要根據所需條件進行表格的組裝,組裝好上傳到服務器後,而後跳轉到前臺直接顯示下載框,下載便可。服務器
前臺jsp部分:app
<li><a class="icon" href="<%=basePath%>feedback/expFeedBack" ><span>導出信息</span></a></li>
Controller部分:webapp
public void expFeedBack(){ String time=""; int count = 0; String mypath=""; try { List<FeedBack> list = FeedBack.dao.find("select f.id,f.content,f.datatime,f.tele from feedback f"); count = list.size(); time = DateUtil.formatDate(); String path = new File("").getAbsolutePath().replaceAll("\\\\", "/"); //得到Tomcat的默認路徑 mypath = path.substring(0,path.lastIndexOf("/"))+"/webapps/3d/excel/"+time+"-"+count+"條.xlsx"; //截取字符串 FileOutputStream os = new FileOutputStream(mypath); Workbook workBook = new SXSSFWorkbook(100); // 只在內存中保留100行記錄 Sheet sheet = workBook.createSheet(); try { int i=0; Row row1 = sheet.createRow(i++); Cell cell = row1.createCell(0); cell.setCellValue("id"); cell = row1.createCell(1); cell.setCellValue("反饋內容"); cell = row1.createCell(2); cell.setCellValue("反饋時間"); cell = row1.createCell(3); cell.setCellValue("聯繫方式"); cell = row1.createCell(4); for (int j = 0; j < list.size(); j++) { row1 = sheet.createRow(i++); cell = row1.createCell(0); cell.setCellValue(list.get(j).getInt("id")); cell = row1.createCell(1); cell.setCellValue(list.get(j).getStr("content")); cell = row1.createCell(2); cell.setCellValue(list.get(j).getStr("datatime")); cell = row1.createCell(3); cell.setCellValue(list.get(j).getStr("tele")); cell = row1.createCell(4); } workBook.write(os); }catch(Exception e){ e.printStackTrace(); } } catch (FileNotFoundException e1) { e1.printStackTrace(); } //判斷路徑是否存在 if(new File(mypath).isFile()){ renderFile(new File(mypath)); }else{ renderNull(); } }
而後就愉快的能夠下載了jsp
方案二:jsp頁面作成的下載【給人以假象的感受】ui
jsp導出excel其實就是後臺查詢完數據放入list集合中,而後跳轉到jsp,而後jsp按照規定的格式顯示出來,而且前臺彈出框,因此就有了jsp下載excelspa
前臺jsp部分:3d
<li><a class="icon" href="<%=basePath%>feedback/expFeedBack" ><span>導出信息</span></a></li>
而後就是後臺部分:
setAttr("feedBackList", FeedBack.dao.find("select * from feedback")); renderJsp("/admin/download.jsp");
這裏的download.jsp是我作的一個下載彈出框要彈出格式的頁面,內容以下
<%@ page contentType="application/vnd.ms-excel; charset=gbk" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <%@ page language="java" pageEncoding="GBK" import="com.dxcm.common.util.*"%> <% String time = DateUtil.formatDate(); String filename = new String((time).getBytes("GBK"),"ISO-8859-1"); response.setHeader("Content-disposition","attachment; filename="+filename+".xls"); %> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=gb2312"> </head> <body > <table border="1"> <tr> <td>ID</td> <td>反饋內容</td> <td>反饋時間</td> <td>聯繫方式</td> </tr> <c:forEach items="${feedBackList}" var ="f"> <tr> <td>${f.id}</td> <td>${f.content}</td> <td>${f.datatime}</td> <td>${f.tele}</td> </tr> </c:forEach> </table> </body> </html>
這裏我用的是EL表達式遍歷的後臺傳出來的集合。
以上代碼屬本人概括總結,若有問題,還請多多指教。