java之poi操作excel-批量导入导出


    上一篇博文介绍了poi操作excel的基本读写操作后,接下来,介绍一下在项目中的实际用途:批量导入、批量导出功能。因为重点知识介绍批量导入导出excel功能,故而项目整体的搭建后台用jdbc与struts2,前端页面用jquery-easyui实现(其实也可以整合到ssm或者ssh中,有需要者可以加我qq:1974544863,愿意带酬劳为你定制开发)。

    首先,看一下,项目的整体结构图:

java之poi操作excel-批量导入导出       java之poi操作excel-批量导入导出


     首先,当然是放入jar包啦,可以来这我这里下载:poi批量导入导出的jar包

     加入jquery-easyui-1.3.3,可以到easyui官网下载,配置web.xml:

[html] view plain copy
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  3.     xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee"  
  4.     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"  
  5.     id="WebApp_ID" version="2.5">  
  6.     <display-name>PoiDemo</display-name>  
  7.     <welcome-file-list>  
  8.         <welcome-file>index.htm</welcome-file>  
  9.     </welcome-file-list>  
  10.     <filter>  
  11.         <filter-name>StrutsPrepareAndExecuteFilter</filter-name>  
  12.         <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter  
  13.         </filter-class>  
  14.     </filter>  
  15.     <filter-mapping>  
  16.         <filter-name>StrutsPrepareAndExecuteFilter</filter-name>  
  17.         <url-pattern>/*</url-pattern>  
  18.     </filter-mapping>  
  19. </web-app>  

    src目录下建立各个包,具体我就不说了,看上面的图即可。新建struts.xml:

[html] view plain copy
  1. <?xml version="1.0" encoding="UTF-8" ?>  
  2. <!DOCTYPE struts PUBLIC  
  3.     "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"  
  4.     "http://struts.apache.org/dtds/struts-2.3.dtd">  
  5.   
  6. <struts>  
  7.       
  8.     <package name="userInfo" namespace="/" extends="struts-default">  
  9.         <action name="user" class="com.steadyjack.action.UserAction">  
  10.         </action>  
  11.   
  12.     </package>  
  13.        
  14. </struts>  
    接下来,介绍com.steadyjack.util下的各个工具类,有一些比较简单,我就不详细说了,注释写得很清楚了!

    DateUtil.java:

[java] view plain copy
  1. package com.steadyjack.util;  
  2.   
  3. import java.text.SimpleDateFormat;  
  4. import java.util.Date;  
  5.   
  6. /** 
  7.  * 简单日期处理工具 
  8.  * @author 钟林森 
  9.  * 
  10.  */  
  11. public class DateUtil {  
  12.   
  13.     public static String formatDate(Date date,String format){  
  14.         String result="";  
  15.         SimpleDateFormat sdf=new SimpleDateFormat(format);  
  16.         if(date!=null){  
  17.             result=sdf.format(date);  
  18.         }  
  19.         return result;  
  20.     }  
  21.       
  22.       
  23.     public static Date formatString(String str,String format) throws Exception{  
  24.         SimpleDateFormat sdf=new SimpleDateFormat(format);  
  25.         return sdf.parse(str);  
  26.     }  
  27.       
  28.     public static void main(String[] args) throws Exception{  
  29.         Date date=formatString("1993/10/12""yyyy/MM/dd");  
  30.         String str=formatDate(date, "yyyy-MM-dd");  
  31.         System.out.println(str);  
  32.     }  
  33. }  

    DbUtil.java:

[java] view plain copy
  1. package com.steadyjack.util;  
  2.   
  3. import java.sql.Connection;  
  4. import java.sql.DriverManager;  
  5.   
  6. /** 
  7.  * 数据库链接工具 
  8.  * @author 钟林森 
  9.  * 
  10.  */  
  11. public class DbUtil {  
  12.   
  13.     private String dbUrl="jdbc:mysql://localhost:3306/db_poi";  
  14.     private String dbUserName="root";  
  15.     private String dbPassword="123456";  
  16.     private String jdbcName="com.mysql.jdbc.Driver";  
  17.       
  18.     public Connection getCon()throws Exception{  
  19.         Class.forName(jdbcName);  
  20.         Connection con=DriverManager.getConnection(dbUrl,dbUserName,dbPassword);  
  21.         return con;  
  22.     }  
  23.       
  24.     public void closeCon(Connection con)throws Exception{  
  25.         if(con!=null){  
  26.             con.close();  
  27.         }  
  28.     }  
  29. }  

     excel导入导出工具类,这个很重要,ExcelUtil.java:

[java] view plain copy
  1. package com.steadyjack.util;  
  2.   
  3. import java.io.InputStream;  
  4. import java.sql.ResultSet;  
  5. import java.text.SimpleDateFormat;  
  6. import java.util.Date;  
  7.   
  8. import org.apache.poi.hssf.usermodel.HSSFCell;  
  9. import org.apache.poi.hssf.usermodel.HSSFDateUtil;  
  10. import org.apache.poi.hssf.usermodel.HSSFWorkbook;  
  11. import org.apache.poi.poifs.filesystem.POIFSFileSystem;  
  12. import org.apache.poi.ss.usermodel.Row;  
  13. import org.apache.poi.ss.usermodel.Sheet;  
  14. import org.apache.poi.ss.usermodel.Workbook;  
  15.   
  16. /** 
  17.  * Excel文件处理工具类: 包括填充数据到普通excel、模板excel文件,单元格格式处理 
  18.  * @author 钟林森 
  19.  * 
  20.  */  
  21. public class ExcelUtil {  
  22.   
  23.     /** 
  24.      * 填充数据到普通的excel文件中 
  25.      * @param rs 
  26.      * @param wb 
  27.      * @param headers 
  28.      * @throws Exception 
  29.      */  
  30.     public static void fillExcelData(ResultSet rs,Workbook wb,String[] headers)throws Exception{  
  31.         Sheet sheet=wb.createSheet();  
  32.         Row row=sheet.createRow(0);  
  33.           
  34.         //先填充行头 : "编号","姓名","电话","Email","QQ","出生日期"  
  35.         for(int i=0;i<headers.length;i++){  
  36.             row.createCell(i).setCellValue(headers[i]);  
  37.         }  
  38.           
  39.         //再填充数据  
  40.         int rowIndex=1;  
  41.         while(rs.next()){  
  42.             row=sheet.createRow(rowIndex++);  
  43.             for(int i=0;i<headers.length;i++){  
  44.                 Object objVal=rs.getObject(i+1);  
  45.                 if (objVal instanceof Date) {  
  46.                     row.createCell(i).setCellValue(DateUtil.formatDate((Date)objVal,"yyyy-MM-dd"));  
  47.                 }else{  
  48.                     row.createCell(i).setCellValue(objVal.toString());  
  49.                 }  
  50.             }  
  51.         }  
  52.     }  
  53.       
  54.     /** 
  55.      * 填充数据到模板excel文件 
  56.      * @param rs 
  57.      * @param templateFileName 
  58.      * @return 
  59.      * @throws Exception 
  60.      */  
  61.     public static Workbook fillExcelDataWithTemplate(ResultSet rs,String templateFileName)throws Exception{  
  62.         //首先:从本地磁盘读取模板excel文件,然后读取第一个sheet  
  63.         InputStream inp=ExcelUtil.class.getResourceAsStream("/com/steadyjack/template/"+templateFileName);  
  64.         POIFSFileSystem fs=new POIFSFileSystem(inp);  
  65.         Workbook wb=new HSSFWorkbook(fs);  
  66.         Sheet sheet=wb.getSheetAt(0);  
  67.           
  68.         //开始写入数据到模板中: 需要注意的是,因为行头以及设置好,故而需要跳过行头  
  69.         int cellNums=sheet.getRow(0).getLastCellNum();  
  70.         int rowIndex=1;  
  71.         while(rs.next()){  
  72.             Row row=sheet.createRow(rowIndex++);  
  73.             for(int i=0;i<cellNums;i++){  
  74.                 Object objVal=rs.getObject(i+1);  
  75.                 if (objVal instanceof Date) {  
  76.                     row.createCell(i).setCellValue(DateUtil.formatDate((Date)objVal,"yyyy-MM-dd"));  
  77.                 }else{  
  78.                     row.createCell(i).setCellValue(objVal.toString());  
  79.                 }  
  80.             }  
  81.         }  
  82.         return wb;  
  83.     }  
  84.       
  85.     /** 
  86.      * 处理单元格格式的简单方式 
  87.      * @param hssfCell 
  88.      * @return 
  89.      */  
  90.     public static String formatCell(HSSFCell hssfCell){  
  91.         if(hssfCell==null){  
  92.             return "";  
  93.         }else{  
  94.             if(hssfCell.getCellType()==HSSFCell.CELL_TYPE_BOOLEAN){  
  95.                 return String.valueOf(hssfCell.getBooleanCellValue());  
  96.             }else if(hssfCell.getCellType()==HSSFCell.CELL_TYPE_NUMERIC){  
  97.                 return String.valueOf(hssfCell.getNumericCellValue());  
  98.             }else{  
  99.                 return String.valueOf(hssfCell.getStringCellValue());  
  100.             }  
  101.         }  
  102.     }  
  103.       
  104.     /** 
  105.      * 处理单元格格式的第二种方式: 包括如何对单元格内容是日期的处理 
  106.      * @param cell 
  107.      * @return 
  108.      */  
  109.     public static String formatCell2(HSSFCell cell) {  
  110.         if (cell.getCellType() == HSSFCell.CELL_TYPE_BOOLEAN) {  
  111.             return String.valueOf(cell.getBooleanCellValue());  
  112.         } else if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {  
  113.               
  114.             //针对单元格式为日期格式  
  115.             if (HSSFDateUtil.isCellDateFormatted(cell)) {  
  116.                 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");  
  117.                 return sdf.format(HSSFDateUtil.getJavaDate(cell.getNumericCellValue())).toString();  
  118.             }  
  119.             return String.valueOf(cell.getNumericCellValue());  
  120.         } else {  
  121.             return cell.getStringCellValue();  
  122.         }  
  123.     }  
  124.   
  125.     /** 
  126.      * 处理单元格格式的第三种方法:比较全面 
  127.      * @param cell 
  128.      * @return 
  129.      */  
  130.     public static String formatCell3(HSSFCell cell) {  
  131.         if (cell == null) {  
  132.             return "";  
  133.         }  
  134.         switch (cell.getCellType()) {  
  135.         case HSSFCell.CELL_TYPE_NUMERIC:  
  136.   
  137.             //日期格式的处理  
  138.             if (HSSFDateUtil.isCellDateFormatted(cell)) {  
  139.                 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");  
  140.                 return sdf.format(HSSFDateUtil.getJavaDate(cell.getNumericCellValue())).toString();  
  141.             }  
  142.   
  143.             return String.valueOf(cell.getNumericCellValue());  
  144.   
  145.             //字符串  
  146.         case HSSFCell.CELL_TYPE_STRING:  
  147.             return cell.getStringCellValue();  
  148.   
  149.             // 公式  
  150.         case HSSFCell.CELL_TYPE_FORMULA:  
  151.             return cell.getCellFormula();  
  152.   
  153.             // 空白  
  154.         case HSSFCell.CELL_TYPE_BLANK:  
  155.             return "";  
  156.   
  157.             // 布尔取值  
  158.         case HSSFCell.CELL_TYPE_BOOLEAN:  
  159.             return cell.getBooleanCellValue() + "";  
  160.               
  161.             //错误类型  
  162.         case HSSFCell.CELL_TYPE_ERROR:  
  163.             return cell.getErrorCellValue() + "";  
  164.         }  
  165.   
  166.         return "";  
  167.     }  
  168. }  

    将jdbc查询得到的ResultSet转为JsonArray工具类JsonUtil.java:

[java] view plain copy
  1. package com.steadyjack.util;  
  2.   
  3. import java.sql.ResultSet;  
  4. import java.sql.ResultSetMetaData;  
  5. import java.util.Date;  
  6.   
  7. import net.sf.json.JSONArray;  
  8. import net.sf.json.JSONObject;  
  9.   
  10. /** 
  11.  * jdbc 的结果集ResultSet转化为JsonArray工具  
  12.  * @author 钟林森 
  13.  * 
  14.  */  
  15. public class JsonUtil {  
  16.   
  17.     /** 
  18.      * 把ResultSet集合转换成JsonArray数组 
  19.      * @param rs 
  20.      * @return 
  21.      * @throws Exception 
  22.      */  
  23.     public static JSONArray formatRsToJsonArray(ResultSet rs)throws Exception{  
  24.         ResultSetMetaData md=rs.getMetaData();  
  25.         int num=md.getColumnCount();  
  26.         JSONArray array=new JSONArray();  
  27.         while(rs.next()){  
  28.             JSONObject mapOfColValues=new JSONObject();  
  29.             for(int i=1;i<=num;i++){  
  30.                   
  31.                 Object strVal=rs.getObject(i);  
  32.                 if (strVal instanceof Date) {  
  33.                     mapOfColValues.put(md.getColumnName(i),DateUtil.formatDate((Date)strVal,"yyyy-MM-dd"));  
  34.                 }else{  
  35.                     mapOfColValues.put(md.getColumnName(i),strVal);  
  36.                 }  
  37.             }  
  38.             array.add(mapOfColValues);  
  39.         }  
  40.         return array;  
  41.     }  
  42. }  

     ResponseUtil.java:

[java] view plain copy
  1. package com.steadyjack.util;  
  2.   
  3. import java.io.OutputStream;  
  4. import java.io.PrintWriter;  
  5.   
  6. import javax.servlet.http.HttpServletResponse;  
  7.   
  8. import org.apache.poi.ss.usermodel.Workbook;  
  9.   
  10. /** 
  11.  * 将数据写回页面 jquery-ajax交互工具类 
  12.  * @author 钟林森 
  13.  * 
  14.  */  
  15. public class ResponseUtil {  
  16.   
  17.     /** 
  18.      * 将数据写回页面 用于jquery-ajax的异步交互 
  19.      * @param response 
  20.      * @param o 
  21.      * @throws Exception 
  22.      */  
  23.     public static void write(HttpServletResponse response,Object o)throws Exception{  
  24.         response.setContentType("text/html;charset=utf-8");  
  25.         PrintWriter out=response.getWriter();  
  26.         out.print(o.toString());  
  27.         out.flush();  
  28.         out.close();  
  29.     }  
  30.       
  31.     /** 
  32.      * 将excel文件写回客户端浏览器 用于下载 
  33.      * @param response 
  34.      * @param wb 
  35.      * @param fileName 
  36.      * @throws Exception 
  37.      */  
  38.     public static void export(HttpServletResponse response,Workbook wb,String fileName)throws Exception{  
  39.         response.setHeader("Content-Disposition""attachment;filename="+new String(fileName.getBytes("utf-8"),"iso8859-1"));  
  40.         response.setContentType("application/ynd.ms-excel;charset=UTF-8");  
  41.         OutputStream out=response.getOutputStream();  
  42.         wb.write(out);  
  43.         out.flush();  
  44.         out.close();  
  45.     }  
  46.   
  47. }  

    StringUtil.java:

[java] view plain copy
  1. package com.steadyjack.util;  
  2.   
  3. /** 
  4.  * 简单字符串处理工具 
  5.  * @author 钟林森 
  6.  * 
  7.  */  
  8. public class StringUtil {  
  9.   
  10.     public static boolean isEmpty(String str){  
  11.         if("".equals(str)||str==null){  
  12.             return true;  
  13.         }else{  
  14.             return false;  
  15.         }  
  16.     }  
  17.       
  18.     public static boolean isNotEmpty(String str){  
  19.         if(!"".equals(str)&&str!=null){  
  20.             return true;  
  21.         }else{  
  22.             return false;  
  23.         }  
  24.     }  
  25. }  

     接下来,是com.steadyjack.model中的User与PageBean:

[java] view plain copy
  1. package com.steadyjack.model;  
  2.   
  3. import java.util.Date;  
  4.   
  5. public class User {  
  6.   
  7.     private int id;  
  8.     private String name;  
  9.     private String phone;  
  10.     private String email;  
  11.     private String qq;  
  12.       
  13.     private Date birth;  
  14.       
  15.     public User() {  
  16.     }  
  17.       
  18.     public User(String name, String phone, String email, String qq) {  
  19.         this.name = name;  
  20.         this.phone = phone;  
  21.         this.email = email;  
  22.         this.qq = qq;  
  23.     }  
  24.       
  25.     public User(String name, String phone, String email, String qq, Date birth) {  
  26.         super();  
  27.         this.name = name;  
  28.         this.phone = phone;  
  29.         this.email = email;  
  30.         this.qq = qq;  
  31.         this.birth = birth;  
  32.     }  
  33.   
  34.     public int getId() {  
  35.         return id;  
  36.     }  
  37.     public void setId(int id) {  
  38.         this.id = id;  
  39.     }  
  40.     public String getName() {  
  41.         return name;  
  42.     }  
  43.     public void setName(String name) {  
  44.         this.name = name;  
  45.     }  
  46.     public String getEmail() {  
  47.         return email;  
  48.     }  
  49.     public void setEmail(String email) {  
  50.         this.email = email;  
  51.     }  
  52.     public String getQq() {  
  53.         return qq;  
  54.     }  
  55.     public void setQq(String qq) {  
  56.         this.qq = qq;  
  57.     }  
  58.     public String getPhone() {  
  59.         return phone;  
  60.     }  
  61.     public void setPhone(String phone) {  
  62.         this.phone = phone;  
  63.     }  
  64.   
  65.     public Date getBirth() {  
  66.         return birth;  
  67.     }  
  68.   
  69.     public void setBirth(Date birth) {  
  70.         this.birth = birth;  
  71.     }  
  72.       
  73. }  

[java] view plain copy
  1. package com.steadyjack.model;  
  2.   
  3. public class PageBean {  
  4.   
  5.     private int page; // 第几页  
  6.     private int rows; // 每页的记录数  
  7.     private int start; // 起始页  
  8.       
  9.     public PageBean(int page, int rows) {  
  10.         super();  
  11.         this.page = page;  
  12.         this.rows = rows;  
  13.     }  
  14.     public int getPage() {  
  15.         return page;  
  16.     }  
  17.     public void setPage(int page) {  
  18.         this.page = page;  
  19.     }  
  20.     public int getRows() {  
  21.         return rows;  
  22.     }  
  23.     public void setRows(int rows) {  
  24.         this.rows = rows;  
  25.     }  
  26.       
  27.     public int getStart() {  
  28.         return (page-1)*rows;  
  29.     }  
  30. }  

     接下来是UserDao(其实,也开发了增删改查的功能,但在这里就不贴出来了,有意者可以加上面的qq联系)

[java] view plain copy
  1. package com.steadyjack.dao;  
  2.   
  3. import java.sql.Connection;  
  4. import java.sql.PreparedStatement;  
  5. import java.sql.ResultSet;  
  6.   
  7. import com.steadyjack.model.PageBean;  
  8. import com.steadyjack.model.User;  
  9.   
  10. public class UserDao {  
  11.   
  12.     public ResultSet userList(Connection con,PageBean pageBean)throws Exception{  
  13.         StringBuffer sb=new StringBuffer("select * from t_user");  
  14.         if(pageBean!=null){  
  15.             sb.append(" limit ?,?");              
  16.         }  
  17.         PreparedStatement pstmt=con.prepareStatement(sb.toString());  
  18.         if(pageBean!=null){  
  19.             pstmt.setInt(1, pageBean.getStart());  
  20.             pstmt.setInt(2, pageBean.getRows());  
  21.         }  
  22.         return pstmt.executeQuery();  
  23.     }  
  24.       
  25.     public int userCount(Connection con)throws Exception{  
  26.         String sql="select count(*) as total from t_user";  
  27.         PreparedStatement pstmt=con.prepareStatement(sql);  
  28.         ResultSet rs=pstmt.executeQuery();  
  29.         if(rs.next()){  
  30.             return rs.getInt("total");  
  31.         }else{  
  32.             return 0;  
  33.         }  
  34.     }  
  35.       
  36.       
  37.       
  38.     public int userAdd(Connection con,User user)throws Exception{  
  39.         String sql="insert into t_user values(null,?,?,?,?,?)";  
  40.         PreparedStatement pstmt=con.prepareStatement(sql);  
  41.         pstmt.setString(1, user.getName());  
  42.         pstmt.setString(2, user.getPhone());  
  43.         pstmt.setString(3, user.getEmail());  
  44.         pstmt.setString(4, user.getQq());  
  45.           
  46.         //java.util.date转为 java.sql.date  
  47.         pstmt.setDate(5new java.sql.Date(user.getBirth() .getTime()));  
  48.           
  49.         return pstmt.executeUpdate();  
  50.     }  
  51. }  

     然后注意com.steadyjack.template下有个 “用户模板文件.xls”,这个可以自己制作:

java之poi操作excel-批量导入导出


    最后是重头戏了UserAction.java:

[java] view plain copy
  1. package com.steadyjack.action;  
  2.   
  3. import java.io.File;  
  4. import java.io.FileInputStream;  
  5. import java.sql.Connection;  
  6. import java.sql.ResultSet;  
  7.   
  8. import net.sf.json.JSONArray;  
  9. import net.sf.json.JSONObject;  
  10.   
  11. import org.apache.poi.hssf.usermodel.HSSFRow;  
  12. import org.apache.poi.hssf.usermodel.HSSFSheet;  
  13. import org.apache.poi.hssf.usermodel.HSSFWorkbook;  
  14. import org.apache.poi.poifs.filesystem.POIFSFileSystem;  
  15. import org.apache.poi.ss.usermodel.Workbook;  
  16. import org.apache.struts2.ServletActionContext;  
  17.   
  18. import com.opensymphony.xwork2.ActionSupport;  
  19. import com.steadyjack.dao.UserDao;  
  20. import com.steadyjack.model.PageBean;  
  21. import com.steadyjack.model.User;  
  22. import com.steadyjack.util.DateUtil;  
  23. import com.steadyjack.util.DbUtil;  
  24. import com.steadyjack.util.ExcelUtil;  
  25. import com.steadyjack.util.JsonUtil;  
  26. import com.steadyjack.util.ResponseUtil;  
  27. import com.steadyjack.util.StringUtil;  
  28.   
  29. public class UserAction extends ActionSupport {  
  30.   
  31.     /** 
  32.      *  
  33.      */  
  34.     private static final long serialVersionUID = 1L;  
  35.   
  36.     private String page;  
  37.     private String rows;  
  38.     private String id;  
  39.     private User user;  
  40.     private String delId;  
  41.       
  42.     private File userUploadFile;  
  43.       
  44.     public String getPage() {  
  45.         return page;  
  46.     }  
  47.     public void setPage(String page) {  
  48.         this.page = page;  
  49.     }  
  50.     public String getRows() {  
  51.         return rows;  
  52.     }  
  53.     public void setRows(String rows) {  
  54.         this.rows = rows;  
  55.     }  
  56.       
  57.     public String getDelId() {  
  58.         return delId;  
  59.     }  
  60.     public void setDelId(String delId) {  
  61.         this.delId = delId;  
  62.     }  
  63.     public User getUser() {  
  64.         return user;  
  65.     }  
  66.     public void setUser(User user) {  
  67.         this.user = user;  
  68.     }  
  69.       
  70.       
  71.     public String getId() {  
  72.         return id;  
  73.     }  
  74.     public void setId(String id) {  
  75.         this.id = id;  
  76.     }  
  77.   
  78.     public File getUserUploadFile() {  
  79.         return userUploadFile;  
  80.     }  
  81.     public void setUserUploadFile(File userUploadFile) {  
  82.         this.userUploadFile = userUploadFile;  
  83.     }  
  84.   
  85.     DbUtil dbUtil=new DbUtil();  
  86.     UserDao userDao=new UserDao();  
  87.       
  88.     //获取用户列表  
  89.     public String list()throws Exception{  
  90.         Connection con=null;  
  91.         PageBean pageBean=new PageBean(Integer.parseInt(page),Integer.parseInt(rows));  
  92.         try{  
  93.             con=dbUtil.getCon();  
  94.             JSONObject result=new JSONObject();  
  95.             JSONArray jsonArray=JsonUtil.formatRsToJsonArray(userDao.userList(con, pageBean));  
  96.             int total=userDao.userCount(con);  
  97.             result.put("rows", jsonArray);  
  98.             result.put("total", total);  
  99.             ResponseUtil.write(ServletActionContext.getResponse(),result);  
  100.         }catch(Exception e){  
  101.             e.printStackTrace();  
  102.         }finally{  
  103.             try {  
  104.                 dbUtil.closeCon(con);  
  105.             } catch (Exception e) {  
  106.                 e.printStackTrace();  
  107.             }  
  108.         }  
  109.         return null;  
  110.     }  
  111.       
  112.     //导出用户  : 普通excel导出  
  113.     public String export()throws Exception{  
  114.         Connection con=null;  
  115.         try {  
  116.             con=dbUtil.getCon();  
  117.             Workbook wb=new HSSFWorkbook();  
  118.             String headers[]={"编号","姓名","电话","Email","QQ","出生日期"};  
  119.             ResultSet rs=userDao.userList(con, null);  
  120.             ExcelUtil.fillExcelData(rs, wb, headers);  
  121.             ResponseUtil.export(ServletActionContext.getResponse(), wb, "用户excel表.xls");  
  122.         } catch (Exception e) {  
  123.             e.printStackTrace();  
  124.         }finally{  
  125.             try {  
  126.                 dbUtil.closeCon(con);  
  127.             } catch (Exception e) {  
  128.                 e.printStackTrace();  
  129.             }  
  130.         }  
  131.         return null;  
  132.     }  
  133.       
  134.     //用户导出 : 采用预先设置好的excel模板文件进行导出  
  135.     public String export2()throws Exception{  
  136.         Connection con=null;  
  137.         try {  
  138.             con=dbUtil.getCon();  
  139.             ResultSet rs=userDao.userList(con, null);  
  140.             Workbook wb=ExcelUtil.fillExcelDataWithTemplate(rs, "用户模板文件.xls");  
  141.             ResponseUtil.export(ServletActionContext.getResponse(), wb, "利用模版导出用户excel表.xls");  
  142.         } catch (Exception e) {  
  143.             e.printStackTrace();  
  144.         }finally{  
  145.             try {  
  146.                 dbUtil.closeCon(con);  
  147.             } catch (Exception e) {  
  148.                 e.printStackTrace();  
  149.             }  
  150.         }  
  151.         return null;  
  152.     }  
  153.       
  154.   
  155.     //excel文件导入,批量导入数据  
  156.     public String upload()throws Exception{  
  157.         //此时的Workbook应该是从 客户端浏览器上传过来的 uploadFile了,其实跟读取本地磁盘的一个样  
  158.         POIFSFileSystem fs=new POIFSFileSystem(new FileInputStream(userUploadFile));  
  159.         HSSFWorkbook wb=new HSSFWorkbook(fs);  
  160.         HSSFSheet hssfSheet=wb.getSheetAt(0);  
  161.           
  162.         if(hssfSheet!=null){  
  163.             //遍历excel,从第二行开始 即 rowNum=1,逐个获取单元格的内容,然后进行格式处理,最后插入数据库  
  164.             for(int rowNum=1;rowNum<=hssfSheet.getLastRowNum();rowNum++){  
  165.                 HSSFRow hssfRow=hssfSheet.getRow(rowNum);  
  166.                 if(hssfRow==null){  
  167.                     continue;  
  168.                 }  
  169.                   
  170.                 User user=new User();  
  171.                 user.setName(ExcelUtil.formatCell(hssfRow.getCell(0)));  
  172.                 user.setPhone(ExcelUtil.formatCell(hssfRow.getCell(1)));  
  173.                 user.setEmail(ExcelUtil.formatCell(hssfRow.getCell(2)));  
  174.                 user.setQq(ExcelUtil.formatCell(hssfRow.getCell(3)));  
  175.                   
  176.                 //对于单元格日期需要进行特殊处理  
  177.                 user.setBirth(DateUtil.formatString(ExcelUtil.formatCell2(hssfRow.getCell(4)), "yyyy-MM-dd"));  
  178.                 Connection con=null;  
  179.                 try{  
  180.                     con=dbUtil.getCon();  
  181.                     userDao.userAdd(con, user);  
  182.                 }catch(Exception e){  
  183.                     e.printStackTrace();  
  184.                 }finally{  
  185.                     dbUtil.closeCon(con);  
  186.                 }  
  187.             }  
  188.         }  
  189.         JSONObject result=new JSONObject();  
  190.         result.put("success""true");  
  191.         ResponseUtil.write(ServletActionContext.getResponse(), result);  
  192.         return null;  
  193.     }  
  194.       
  195. }  

     最后有一个WebContent目录下template文件夹有个userTemplateFile.xls,跟“用户模板文件.xls”是一模一样的,只是换个名字而已。

     最后当然是页面了crud1.html:

[html] view plain copy
  1. <!DOCTYPE html>  
  2. <html>  
  3. <head>  
  4.     <meta charset="UTF-8">  
  5.     <title>poi操作excel</title>  
  6.     <link rel="stylesheet" type="text/css" href="jquery-easyui-1.3.3/themes/default/easyui.css">  
  7.     <link rel="stylesheet" type="text/css" href="jquery-easyui-1.3.3/themes/icon.css">  
  8.     <script type="text/javascript" src="jquery-easyui-1.3.3/jquery.min.js"></script>  
  9.     <script type="text/javascript" src="jquery-easyui-1.3.3/jquery.easyui.min.js"></script>  
  10.     <script type="text/javascript" src="jquery-easyui-1.3.3/locale/easyui-lang-zh_CN.js"></script>  
  11.     <script>  
  12.         var url;  
  13.         function deleteUser(){  
  14.             var row=$('#dg').datagrid('getSelected');  
  15.             if(row){  
  16.                 $.messager.confirm("系统提示","您确定要删除这条记录吗?",function(r){  
  17.                     if(r){  
  18.                         $.post('user!delete',{delId:row.id},function(result){  
  19.                             if(result.success){  
  20.                                 $.messager.alert("系统提示","已成功删除这条记录!");  
  21.                                 $("#dg").datagrid("reload");  
  22.                             }else{  
  23.                                 $.messager.alert("系统提示",result.errorMsg);  
  24.                             }  
  25.                         },'json');  
  26.                     }  
  27.                 });  
  28.             }  
  29.         }  
  30.           
  31.         function newUser(){  
  32.             $("#dlg").dialog('open').dialog('setTitle','添加用户');  
  33.             $('#fm').form('clear');  
  34.             url='user!save';  
  35.         }  
  36.           
  37.           
  38.         function editUser(){  
  39.             var row=$('#dg').datagrid('getSelected');  
  40.             if(row){  
  41.                 $("#dlg").dialog('open').dialog('setTitle','编辑用户');  
  42.                 $("#name").val(row.name);  
  43.                 $("#phone").val(row.phone);  
  44.                 $("#email").val(row.email);  
  45.                 $("#qq").val(row.qq);  
  46.                 url='user!save?id='+row.id;  
  47.             }  
  48.         }  
  49.           
  50.           
  51.         function saveUser(){  
  52.             $('#fm').form('submit',{  
  53.                 url:url,  
  54.                 onSubmit:function(){  
  55.                     return $(this).form('validate');  
  56.                 },  
  57.                 success:function(result){  
  58.                     var result=eval('('+result+')');  
  59.                     if(result.errorMsg){  
  60.                         $.messager.alert("系统提示",result.errorMsg);  
  61.                         return;  
  62.                     }else{  
  63.                         $.messager.alert("系统提示","保存成功");  
  64.                         $('#dlg').dialog('close');  
  65.                         $("#dg").datagrid("reload");  
  66.                     }  
  67.                 }  
  68.             });  
  69.         }  
  70.           
  71.           
  72.         function exportUser(){  
  73.             window.open('user!export');  
  74.         }  
  75.       
  76.         function exportUser2(){  
  77.             window.open('user!export2');  
  78.         }  
  79.           
  80.         function openUploadFileDialog(){  
  81.             $("#dlg2").dialog('open').dialog('setTitle','批量导入数据');  
  82.         }  
  83.           
  84.         function downloadTemplate(){  
  85.             window.open('template/userTemplateFile.xls');  
  86.         }  
  87.           
  88.         function uploadFile(){  
  89.             $("#uploadForm").form("submit",{  
  90.                 success:function(result){  
  91.                     var result=eval('('+result+')');  
  92.                     if(result.errorMsg){  
  93.                         $.messager.alert("系统提示",result.errorMsg);  
  94.                     }else{  
  95.                         $.messager.alert("系统提示","上传成功");  
  96.                         $("#dlg2").dialog("close");  
  97.                         $("#dg").datagrid("reload");  
  98.                     }  
  99.                 }  
  100.             });  
  101.         }  
  102.           
  103.     </script>  
  104. </head>  
  105. <body>  
  106.     <table id="dg" title="用户管理" class="easyui-datagrid" style="width:700px;height:365px"  
  107.             url="user!list"  
  108.             toolbar="#toolbar" pagination="true"  
  109.             rownumbers="true" fitColumns="true" singleSelect="true">  
  110.         <thead>  
  111.             <tr>  
  112.                 <th field="id" width="50" hidden="true">编号</th>  
  113.                 <th field="name" width="50">姓名</th>  
  114.                 <th field="phone" width="50">电话</th>  
  115.                 <th field="email" width="50">Email</th>  
  116.                 <th field="qq" width="50">QQ</th>  
  117.                 <th field="birth" width="50">出生日期</th>  
  118.             </tr>  
  119.         </thead>  
  120.     </table>  
  121.     <div id="toolbar">  
  122.         <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-add" plain="true" onclick="newUser()">添加用户</a>  
  123.         <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-edit" plain="true" onclick="editUser()">编辑用户</a>  
  124.         <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-remove" plain="true" onclick="deleteUser()">删除用户</a>  
  125.         <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-export" plain="true" onclick="exportUser()">导出用户</a>  
  126.         <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-export" plain="true" onclick="exportUser2()">用模版导出用户</a>  
  127.         <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-import" plain="true" onclick="openUploadFileDialog()">用模版批量导入数据</a>  
  128.     </div>  
  129.       
  130.     <div id="dlg" class="easyui-dialog" style="width:400px;height:250px;padding:10px 20px"  
  131.             closed="true" buttons="#dlg-buttons">  
  132.         <form id="fm"  method="post">  
  133.             <table cellspacing="10px;">  
  134.                 <tr>  
  135.                     <td>姓名:</td>  
  136.                     <td><input id="name"  name="user.name" class="easyui-validatebox" required="true" style="width: 200px;"></td>  
  137.                 </tr>  
  138.                 <tr>  
  139.                     <td>联系电话:</td>  
  140.                     <td><input id="phone"  name="user.phone" class="easyui-validatebox" required="true" style="width: 200px;"></td>  
  141.                 </tr>  
  142.                 <tr>  
  143.                     <td>Email:</td>  
  144.                     <td><input id="email"  name="user.email" class="easyui-validatebox" validType="email" required="true" style="width: 200px;"></td>  
  145.                 </tr>  
  146.                 <tr>  
  147.                     <td>QQ:</td>  
  148.                     <td><input id="qq" name="user.qq" class="easyui-validatebox" required="true" style="width: 200px;"></td>  
  149.                 </tr>  
  150.                 <tr>  
  151.                     <td>出生日期:</td>  
  152.                     <td><input id="birth" name="user.birth" class="easyui-validatebox" required="true" style="width: 200px;"></td>  
  153.                 </tr>  
  154.             </table>  
  155.         </form>  
  156.     </div>  
  157.       
  158.     <div id="dlg-buttons">  
  159.         <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-ok" onclick="saveUser()">保存</a>  
  160.         <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-cancel" onclick="javascript:$('#dlg').dialog('close')">关闭</a>  
  161.     </div>  
  162.       
  163.       
  164.     <div id="dlg2" class="easyui-dialog" style="width:400px;height:180px;padding:10px 20px"  
  165.             closed="true" buttons="#dlg-buttons2">  
  166.         <form id="uploadForm" action="user!upload" method="post" enctype="multipart/form-data">  
  167.             <table>  
  168.                 <tr>  
  169.                     <td>下载模版:</td>  
  170.                     <td><a href="javascript:void(0)" class="easyui-linkbutton"  onclick="downloadTemplate()">下载模板文件</a></td>  
  171.                 </tr>  
  172.                 <tr>  
  173.                     <td>上传文件:</td>  
  174.                     <td><input type="file" name="userUploadFile"></td>  
  175.                 </tr>  
  176.             </table>  
  177.         </form>  
  178.     </div>  
  179.       
  180.     <div id="dlg-buttons2">  
  181.         <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-ok" onclick="uploadFile()">上传</a>  
  182.         <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-cancel" onclick="javascript:$('#dlg2').dialog('close')">关闭</a>  
  183.     </div>  
  184.       
  185. </body>  
  186. </html>  

    其中,添加、删除、修改的功能已经实现了,但代码我就不贴出来了,因为我重点是介绍批量导入导出excel。

    当然啦,需要新建一个数据库db_poi,新建一个数据库表t_user:

[plain] view plain copy
  1. DROP TABLE IF EXISTS `t_user`;  
  2. CREATE TABLE `t_user` (  
  3.   `id` int(11) NOT NULL AUTO_INCREMENT,  
  4.   `name` varchar(20) DEFAULT NULL,  
  5.   `phone` varchar(20) DEFAULT NULL,  
  6.   `email` varchar(20) DEFAULT NULL,  
  7.   `qq` varchar(20) DEFAULT NULL,  
  8.   `birth` datetime DEFAULT NULL,  
  9.   PRIMARY KEY (`id`)  
  10. ) ENGINE=InnoDB AUTO_INCREMENT=65 DEFAULT CHARSET=utf8;  
  11.   
  12.   
  13. INSERT INTO `t_user` VALUES ('51', '钟林森', '12121212', '[email protected]', '121212121212122', '2016-10-11 22:36:57');  
  14. INSERT INTO `t_user` VALUES ('54', 'steadyjack', '11111', '[email protected]', '1111122222121212', '2016-10-28 22:37:06');  
  15. INSERT INTO `t_user` VALUES ('55', '钟林森', '22222', '[email protected]', '2222211111121212', '2016-10-20 22:37:09');  
  16. INSERT INTO `t_user` VALUES ('56', '钟稳杰', '33333', '[email protected]', '3333322222121212', '2016-10-13 22:37:12');  

    在tomcat跑起来,下面是运行效果:

java之poi操作excel-批量导入导出


    点击“导出用户”,即可下载得到“用户excel表.xls”,打开来瞧瞧,是否跟上图的数据一致:

java之poi操作excel-批量导入导出


    发现一致是一致,但是就是丑陋了点。接下来,我们“用模板导出用户”,可以得到比较好看的数据:

java之poi操作excel-批量导入导出


     最后,点击“用模板批量导入数据”:

java之poi操作excel-批量导入导出


    可以先下载模板文件,填写好数据之后,再回来这里“选择文件”,上传填写好数据的那个excel文件,下面是我弄好的几条数据:

java之poi操作excel-批量导入导出


    最后,上传这个文件,导入进去,再回来首页看看:

java之poi操作excel-批量导入导出


java之poi操作excel-批量导入导出

   

    关于导入,目前还没有去深入搞:“判断一些是否合法,如何将不合法的数据再导入完成之后提示或者展示给用户观看。。。”这些,自己也在搞中,有兴趣的,可以加qq交流!