在開發過程當中,須要將數據庫中的數據以excel表格的方式導出。javascript
首先說明。我這裏用的是Apache的POI項目,它是目前比較成熟的HSSF接口,用來處理Excel對象。其實POI不單單隻能處理excel,它還能夠處理word、PowerPoint、Visio、甚至Outlook。html
一.首先介紹利用POI如何生成excel。 java
首先在生成Excel前,咱們須要理解一下Excel文件的組織形式。在POI中,是這樣理解的:一個Excel文件對應一個workbook,一個workerbook是有若干個sheet組成的。一個sheet有多個row,一個row通常存在多個cell。web
對於上面的四個名詞咱們能夠在下圖理解:ajax
對於生成Excel,POI提供了以下幾個基本對象:spring
HSSFWorkbook excel 的文檔對象數據庫
HSSFSheet excel 的表單apache
HSSFRow excel 的行瀏覽器
HSSFCell excel 的格子單元app
從上面的圖片和Excel的組織結構,咱們就能夠明白建立Excel的步驟。
一、生成文檔對象HSSHWorkbook。
二、經過HSSFWorkbook生成表單HSSFSheet。
三、經過HSSFSheet生成行HSSFRow
四、經過HSSFRow生成單元格HSSFCell。
下面展現代碼:
第一步、導入jar包
<dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.9</version> </dependency>
第二步,建立Model對象
public class Person { private String id; private String name; private String password; private String age; public Person(String id, String name, String password, String age) { super(); this.id = id; this.name = name; this.password = password; this.age = age; } //提供set和get方法 }
第三步.下載界面 exportexcel.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <html> <!-- 正常數據導出確定要傳入參數,我這裏沒有用ajax傳參,簡單用連接傳參 --> <script type="text/javascript"> function download(){ var url="download_excel?id=10&name=張三"; window.open(url); } </script> <body> <form action=""> <input type="button" value="報表導出" onclick="download()"/> </form> </body> </html>
第四步、ExcleController.java
import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import com.ssm.service.impl.ExcleImpl; @Controller public class ExcleController { //這裏直接new了 ExcleImpl excleImpl=new ExcleImpl(); @RequestMapping(value="/jsp/download_excel") //獲取url連接上的參數 public @ResponseBody String dowm(HttpServletResponse response,@RequestParam("id") String id,@RequestParam("name") String name){ response.setContentType("application/binary;charset=UTF-8"); try{ ServletOutputStream out=response.getOutputStream(); try { //設置文件頭:最後一個參數是設置下載文件名(這裏咱們叫:張三.pdf) response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(name+".xls", "UTF-8")); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); } String[] titles = { "用戶id", "用戶姓名", "用戶密碼", "用戶年齡" }; excleImpl.export(titles, out); return "success"; } catch(Exception e){ e.printStackTrace(); return "導出信息失敗"; } } }
第五步、ExcleImpl 報表導出實現層
import java.util.ArrayList; import javax.servlet.ServletOutputStream; 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 com.ssm.model.Person; public class ExcleImpl { public void export(String[] titles, ServletOutputStream out) throws Exception{ try{ // 第一步,建立一個workbook,對應一個Excel文件 HSSFWorkbook workbook = new HSSFWorkbook(); // 第二步,在webbook中添加一個sheet,對應Excel文件中的sheet HSSFSheet hssfSheet = workbook.createSheet("sheet1"); // 第三步,在sheet中添加表頭第0行,注意老版本poi對Excel的行數列數有限制short HSSFRow row = hssfSheet.createRow(0); // 第四步,建立單元格,並設置值表頭 設置表頭居中 HSSFCellStyle hssfCellStyle = workbook.createCellStyle(); //居中樣式 hssfCellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); HSSFCell hssfCell = null; for (int i = 0; i < titles.length; i++) { hssfCell = row.createCell(i);//列索引從0開始 hssfCell.setCellValue(titles[i]);//列名1 hssfCell.setCellStyle(hssfCellStyle);//列居中顯示 } // 第五步,寫入實體數據 Person person1=new Person("1","張三","123","26"); Person person2=new Person("2","李四","123","18"); Person person3=new Person("3","王五","123","77"); Person person4=new Person("4","徐小筱","123","1"); //這裏我把list當作數據庫啦 ArrayList<Person> list=new ArrayList<Person>(); list.add(person1); list.add(person2); list.add(person3); list.add(person4); for (int i = 0; i < list.size(); i++) { row = hssfSheet.createRow(i+1); Person person = list.get(i); // 第六步,建立單元格,並設置值 String id = null; if(person.getId() != null){ id = person.getId(); } row.createCell(0).setCellValue(id); String name = ""; if(person.getName() != null){ name = person.getName(); } row.createCell(1).setCellValue(name); String password = ""; if(person.getPassword() != null){ password = person.getPassword(); } row.createCell(2).setCellValue(password); String age=null; if(person.getAge() !=null){ age = person.getAge(); } row.createCell(3).setCellValue(age); } // 第七步,將文件輸出到客戶端瀏覽器 try { workbook.write(out); out.flush(); out.close(); } catch (Exception e) { e.printStackTrace(); } }catch(Exception e){ e.printStackTrace(); throw new Exception("導出信息失敗!"); } } }
第六步:最終效果,當我點擊報表導出按鈕
完美!