javaweb中如何使用POI把資料匯出為Excel(有下載提示框)詳細教程
阿新 • • 發佈:2019-02-11
準備步驟:
1.首先要在Apache官網上下載poi的jar包(以poi-3.17為例)
3.下載完成後解壓檔案
4.將裡面的jar包都引到專案中去,也可以單獨引poi的jar包
示例程式碼:
package com.lzy.Controller; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFCellStyle; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.HorizontalAlignment; import com.lzy.dao.LoginDao; import com.lzy.dao.UserDao; import com.lzy.entity.LoginLog; import com.lzy.entity.Users; import com.lzy.imp.LoginDaoimpl; import com.lzy.imp.UserDaoimpl; public class Excel extends HttpServlet { /** * Constructor of the object. */ public Excel() { super(); } /** * Destruction of the servlet. <br> */ public void destroy() { super.destroy(); // Just puts "destroy" string in log // Put your code here } /** * The doGet method of the servlet. <br> * * This method is called when a form has its tag value method equals to get. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } /** * The doPost method of the servlet. <br> * * This method is called when a form has its tag value method equals to post. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doPost(HttpServletRequest request, HttpServletResponse res) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); res.setCharacterEncoding("UTF-8"); // 以下為生成Excel操作 // 建立一個workbook,對應一個Excel檔案 HSSFWorkbook wb = new HSSFWorkbook(); // 在workbook中新增一個sheet,對應Excel中的一個sheet HSSFSheet sheet = wb.createSheet("XXX表"); // 在sheet中新增表頭第0行,老版本poi對excel行數列數有限制short HSSFRow row = sheet.createRow((int) 0); // 建立單元格,設定值表頭,設定表頭居中 HSSFCellStyle style = wb.createCellStyle(); // 居中格式 style.setAlignment(HorizontalAlignment.CENTER); // 設定表頭 List<LoginLog> logs = new ArrayList<LoginLog>(); //接受LogListServelt傳過來的日誌集合 logs = (List<LoginLog>) request.getAttribute("sr"); String url = (String) request.getAttribute("url"); Map<Integer,String> users = new HashMap<Integer,String>(); users=(Map<Integer, String>) request.getAttribute("user"); String[] titles =(String[]) request.getAttribute("title"); HSSFCell cell; for(int x=0;x<titles.length;x++){ cell = row.createCell(x); cell.setCellValue(titles[x]); cell.setCellStyle(style); } //生成excel格式後要將資料寫入excel: // 迴圈將資料寫入Excel for (int i = 0; i < logs.size(); i++) { row = sheet.createRow((int) i + 1); LoginLog list= logs.get(i); row.createCell(0).setCellValue(list.getLogId()); row.createCell(1).setCellValue(users.get(list.getUserId())); row.createCell(2).setCellValue(list.getLoginDate()); row.createCell(3).setCellValue(list.getRemoteIP()); row.createCell(4).setCellValue(list.getRemark()); } /*之後將生成的Excel以流輸出。 *不彈出下載框 */ //FileOutputStream out =new FileOutputStream("E:/XXX.xls"); //wb.write(out); //out.close(); //彈出下載框 String fileName = "example"; ByteArrayOutputStream os = new ByteArrayOutputStream(); wb.write(os); byte[] content = os.toByteArray(); InputStream is = new ByteArrayInputStream(content); // 設定response引數,可以開啟下載頁面 res.reset(); //設定編碼格式 res.setContentType("application/vnd.ms-excel;charset=utf-8"); res.setHeader("Content-Disposition", "attachment;filename=" + new String((fileName + ".xls").getBytes(), "iso-8859-1")); ServletOutputStream out1 = res.getOutputStream(); BufferedInputStream bis = null; BufferedOutputStream bos = null; try { bis = new BufferedInputStream(is); bos = new BufferedOutputStream(out1); byte[] buff = new byte[2048]; int bytesRead; // Simple read/write loop. while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) { bos.write(buff, 0, bytesRead); } } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } finally { if (bis != null) bis.close(); if (bos != null) bos.close(); } request.getRequestDispatcher(url).forward(request,res); } /** * The doPut method of the servlet. <br> * * This method is called when a HTTP put request is received. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Put your code here } /** * Initialization of the servlet. <br> * * @throws ServletException if an error occurs */ public void init() throws ServletException { // Put your code here } }
註釋:
1.這是一段我寫好的servelt,用來處理轉出Excel表格!
2.傳入url是為了在處理完成後再跳轉的頁面地址
3.傳入map集合是用來書寫每行的列名
4.res是request