jfinal+poi匯出excel
阿新 • • 發佈:2019-02-13
廢話不說了,開始了!
方案一:JFinal的renderFile("路徑")功能
先說說我的邏輯:
前臺頁面點選請求傳送到後臺Controller,然後Controller層主要根據所需條件進行表格的組裝,組裝好上傳到伺服器後,然後跳轉到前臺直接顯示下載框,下載即可。
前臺jsp部分:
<li><a class="icon" href="<%=basePath%>feedback/expFeedBack" ><span>匯出資訊</span></a></li>
Controller部分:
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匯出excel其實就是後臺查詢完資料放入list集合中,然後跳轉到jsp,然後jsp按照規定的格式顯示出來,並且前臺彈出框,所以就有了jsp下載excel
前臺jsp部分:
<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表示式遍歷的後臺傳出來的集合。
以上程式碼屬本人歸納總結,如有問題,還請多多指教。