Apache POI是Apache軟件基金會的開放源碼函式庫,POI提供API給Java程序對Microsoft Office格式檔案讀和寫的功能。html
這裏的方法支持導出excel至項目所在服務器,或導出至客戶端瀏覽器供用戶下載,下面我把兩個實例都放出來。java
1.下載所需POI的jar包,並導入項目。web
2.添加一個User類,用於存放用戶實體,類中內容以下:spring
1 package com.mvc.po; 2 3 public class User { 4 private int id; 5 private String name; 6 private String password; 7 private int age; 8 9 public User() { 10 11 } 12 13 public User(int id, String name, String password, int age) { 14 this.id = id; 15 this.name = name; 16 this.password = password; 17 this.age = age; 18 } 19 public int getId() { 20 return id; 21 } 22 public void setId(int id) { 23 this.id = id; 24 } 25 public String getName() { 26 return name; 27 } 28 public void setName(String name) { 29 this.name = name; 30 } 31 public String getPassword() { 32 return password; 33 } 34 public void setPassword(String password) { 35 this.password = password; 36 } 37 public int getAge() { 38 return age; 39 } 40 public void setAge(int age) { 41 this.age = age; 42 } 43 }
3.添加一個UserController類,類中內容以下:sql
1 package com.mvc.controller; 2 3 import java.text.SimpleDateFormat; 4 import java.util.Date; 5 6 import javax.servlet.ServletOutputStream; 7 import javax.servlet.http.HttpServletResponse; 8 9 import org.springframework.stereotype.Controller; 10 import org.springframework.beans.factory.annotation.Autowired; 11 import org.springframework.web.bind.annotation.RequestMapping; 12 import org.springframework.web.bind.annotation.ResponseBody; 13 14 import com.mvc.po.User; 15 import com.mvc.service.UserService; 16 17 @Controller 18 public class UserController { 19 20 @Autowired 21 private UserService userService; 22 23 @RequestMapping("/export.do") 24 public @ResponseBody String export(HttpServletResponse response){ 25 response.setContentType("application/binary;charset=UTF-8"); 26 try{ 27 ServletOutputStream out=response.getOutputStream(); 28 String fileName=new String(("UserInfo "+ new SimpleDateFormat("yyyy-MM-dd").format(new Date())).getBytes(),"UTF-8"); 29 response.setHeader("Content-disposition", "attachment; filename=" + fileName + ".xls"); 30 String[] titles = { "用戶編號", "用戶姓名", "用戶密碼", "用戶年齡" }; 31 userService.export(titles, out); 32 return "success"; 33 } catch(Exception e){ 34 e.printStackTrace(); 35 return "導出信息失敗"; 36 } 37 } 38 }
4.添加一個接口類UserService和實現類UserServiceImpl,類中內容以下:apache
1 package com.mvc.service; 2 3 import javax.servlet.ServletOutputStream; 4 import com.mvc.po.User; 5 6 public interface UserService { 7 public void export(String[] titles, ServletOutputStream out); 8 }
1 package com.mvc.service.impl; 2 3 import java.text.SimpleDateFormat; 4 import java.util.List; 5 6 import javax.servlet.ServletOutputStream; 7 8 import com.mvc.dao.UserDAO; 9 import com.mvc.po.User; 10 import com.mvc.service.UserService; 11 12 import org.apache.poi.hssf.usermodel.HSSFCell; 13 import org.apache.poi.hssf.usermodel.HSSFCellStyle; 14 import org.apache.poi.hssf.usermodel.HSSFRow; 15 import org.apache.poi.hssf.usermodel.HSSFSheet; 16 import org.apache.poi.hssf.usermodel.HSSFWorkbook; 17 import org.springframework.beans.factory.annotation.Autowired; 18 import org.springframework.stereotype.Service; 19 20 @Service 21 public class UserServiceImpl implements UserService { 22 23 @Autowired 24 private UserDAO userDAO; 25 26 @Override 27 public void export(String[] titles, ServletOutputStream out) { 28 try{ 29 // 第一步,建立一個workbook,對應一個Excel文件 30 HSSFWorkbook workbook = new HSSFWorkbook(); 31 // 第二步,在webbook中添加一個sheet,對應Excel文件中的sheet 32 HSSFSheet hssfSheet = workbook.createSheet("sheet1"); 33 // 第三步,在sheet中添加表頭第0行,注意老版本poi對Excel的行數列數有限制short 34 HSSFRow hssfRow = hssfSheet.createRow(0); 35 // 第四步,建立單元格,並設置值表頭 設置表頭居中 36 HSSFCellStyle hssfCellStyle = workbook.createCellStyle(); 37 //居中樣式 38 hssfCellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); 39 40 HSSFCell hssfCell = null; 41 for (int i = 0; i < titles.length; i++) { 42 hssfCell = hssfRow.createCell(i);//列索引從0開始 43 hssfCell.setCellValue(titles[i]);//列名1 44 hssfCell.setCellStyle(hssfCellStyle);//列居中顯示 45 } 46 47 // 第五步,寫入實體數據 48 List<User> users = userDAO.query(); 49 50 SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd"); 51 if(users != null && !users.isEmpty()){ 52 for (int i = 0; i < users.size(); i++) { 53 hssfRow = hssfSheet.createRow(i+1); 54 User user = users.get(i); 55 56 // 第六步,建立單元格,並設置值 57 int userid = 0; 58 if(user.getId() != 0){ 59 userid = user.getId(); 60 } 61 hssfRow.createCell(0).setCellValue(userid); 62 String username = ""; 63 if(user.getName() != null){ 64 username = user.getName(); 65 } 66 hssfRow.createCell(1).setCellValue(username); 67 String password = ""; 68 if(user.getPassword() != null){ 69 password = user.getPassword(); 70 } 71 hssfRow.createCell(2).setCellValue(password); 72 int age = 0; 73 if(user.getAge() != 0){ 74 age = user.getAge(); 75 } 76 hssfRow.createCell(3).setCellValue(age); 77 } 78 } 79 80 // 第七步,將文件輸出到客戶端瀏覽器 81 try { 82 workbook.write(out); 83 out.flush(); 84 out.close(); 85 86 } catch (Exception e) { 87 e.printStackTrace(); 88 } 89 }catch(Exception e){ 90 e.printStackTrace(); 91 throw new Exception("導出信息失敗!"); 92 } 93 } 94 }
5.添加一個接口類UserDAO和實現類UserDAOImpl,類中內容以下:瀏覽器
1 package com.mvc.dao; 2 3 import java.util.List; 4 import com.mvc.po.User; 5 6 public interface UserDAO { 7 List<User> query(); 8 }
1 package com.mvc.dao.impl; 2 3 import java.util.List; 4 import java.sql.ResultSet; 5 import java.sql.SQLException; 6 7 import com.mvc.dao.UserDAO; 8 import com.mvc.po.User; 9 10 import org.springframework.stereotype.Repository; 11 import org.springframework.beans.factory.annotation.Autowired; 12 import org.springframework.jdbc.core.JdbcTemplate; 13 import org.springframework.jdbc.core.RowMapper; 14 15 @Repository 16 public class UserDAOImpl implements UserDAO { 17 18 @Autowired 19 private JdbcTemplate jdbcTemplate; 20 21 public List<User> query() { 22 return this.jdbcTemplate.query("select * from student", 23 new RowMapper<User>() { 24 public User mapRow(ResultSet rs, int arg1) 25 throws SQLException { 26 return new User(rs.getInt("sId"), 27 rs.getString("sName"), rs.getString("sPwd"), rs 28 .getInt("sAge")); 29 } 30 }); 31 } 32 }
這樣就完成了excel導出至客戶端瀏覽器,固然有時候也會用到導出excel至服務器上。只須要對本文步驟4中的第七步文件輸出方式進行修改,以下:服務器
1 // 第七步,將文件存到指定位置 2 try { 3 FileOutputStream fileOutputStream = new FileOutputStream("C:/user.xls");//指定路徑與名字和格式 4 workbook.write(fileOutputStream);//將數據寫出去 5 fileOutputStream.close();//關閉輸出流 6 } catch (Exception e) { 7 e.printStackTrace(); 8 }
而後去除controller類中的out參數設置就ok了。也能夠看出其實兩種方式只是最終保存方式不一樣,其餘步驟是共通的。mvc
2017-9-8 更新:HSSF、XSSF和SXSSF區別以及Excel導出優化app