wzh123

博客园 首页 新随笔 联系 订阅 管理

本实例通过struts2+hibernate+poi实现导出数据导入到Excel的功能

 

用到的jar包:

 

 

poi 下载地址:http://poi.apache.org/

根据查询条件的选择显示相应数据到页面,并把数据可导入到Excel表中
首先根据查询条件显示数据
 选择导出Excel将根据查询条件返回数据并通过流写入Excel文件中,核心代码如下:

  1. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>  
  2. <%@ taglib prefix="s" uri="/struts-tags" %>  
  3. <%  
  4. String path = request.getContextPath();  
  5. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  
  6. %>  
  7.   
  8. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  9. <html>  
  10.   <head>  
  11.     <base href="<%=basePath%>">  
  12.       
  13.     <title>My JSP 'list_export.jsp' starting page</title>  
  14.       
  15.     <meta http-equiv="pragma" content="no-cache">  
  16.     <meta http-equiv="cache-control" content="no-cache">  
  17.     <meta http-equiv="expires" content="0">      
  18.     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">  
  19.     <meta http-equiv="description" content="This is my page">  
  20.   
  21. <mce:script type="text/javascript"><!--  
  22.         function toExport(obj){  
  23.             obj.form.act.value = "export";  
  24.             obj.form.submit();  
  25.         }  
  26.   
  27.   
  28.         function toQuery(obj) {  
  29.               obj.form.act.value = "query";  
  30.                var v =document.getElementById ('form1');  
  31.               // alert(v);   
  32.                v.action="criteriaQuery.action";  
  33.               //alert(v.action);   
  34.               obj.form.submit();  
  35.             }  
  36. // --></mce:script>   
  37.   </head>  
  38.     
  39. <body style="overflow-x:hidden;overflow-y:auto;" mce_style="overflow-x:hidden;overflow-y:auto;">  
  40.                         <form name="form" method="post"  id="form1" action="queryExport.action">  
  41.                         <table align="center" width="%100">  
  42.                         <tr>  
  43.                         <td>姓名:<s:textfield name="pram_name"  value="%{#parameters.pram_name}"  theme="simple"/></td>  
  44.                          <td>年龄:<s:textfield name="pram_age"  value="%{#parameters.pram_age}"  theme="simple"/></td>   
  45.                          <td>地址:<s:textfield name="pram_address"  value="%{#parameters.pram_address}"  theme="simple"/> </td>  
  46.                         </tr>  
  47.                         <tr align="right"  >  
  48.                         <td  colspan="3">  
  49.                         <input type="button" value=" 查询 " onclick="toQuery(this)">   
  50.                         </td>  
  51.                         </tr>  
  52.                         </table>  
  53.                         <input type="hidden"  id="act" name="act" >  
  54.                           
  55.                         </form>  
  56.                           
  57.                         <table id="content" cellSpacing="1" cellPadding="0" width="100%"   border="0">  
  58.                             <tr>  
  59.                                 <td align="center">姓名</td>  
  60.                                 <td align="center">年龄</td>  
  61.                                <td align="center">地址</td>  
  62.                               
  63.                             </tr>  
  64.                           <s:iterator value="userInfos">  
  65.                                      <tr>  
  66.                                         <td align="center"><s:property value="name" /></td>  
  67.                                         <td align="center"><s:property value="age" /></td>  
  68.                                         <td align="center"><s:property value="address" /></td>  
  69.                                    </tr>  
  70.                         </s:iterator>  
  71.                           
  72.                         </table>  
  73.                         <table width="100%" border="0" cellspacing="0" cellpadding="0">  
  74.                             <tr>  
  75.                                 <td height="10"></td>  
  76.                             </tr>  
  77.                             <tr>  
  78.                                 <td height="25" align="left">  
  79.                                   <a href="javascript:toExport(this);" mce_href="javascript:toExport(this);"><font color="#2469D7">导出...</font></a></td>  
  80.                             </tr>  
  81.                         </table>  
  82. </body>  
  83. </html>  

 

 

struts.xml

  1. <?xml version="1.0" encoding="UTF-8" ?>  
  2. <!DOCTYPE struts PUBLIC  
  3.     "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"  
  4.     "http://struts.apache.org/dtds/struts-2.0.dtd">  
  5.   
  6. <struts>  
  7.   
  8.     <constant name="struts.enable.DynamicMethodInvocation" value="false" />  
  9.     <constant name="struts.devMode" value="false" />  
  10.   
  11.       
  12.       
  13.     <package name="index" namespace="/" extends="struts-default">  
  14.   
  15.         <action name="listExport" class="com.ywjava.office.action.ListAction">  
  16.             <result>  
  17.                 /WEB-INF/page/list_export.jsp  
  18.             </result>  
  19.         </action>  
  20.           
  21.             <action name="criteriaQuery" class="com.ywjava.office.action.QueryExportAction">  
  22.             <result>  
  23.                 /WEB-INF/page/list_export.jsp  
  24.             </result>  
  25.         </action>  
  26.           
  27.         <action name="queryExport" class="com.ywjava.office.action.QueryExportAction">  
  28.         <result name="success" type="stream">   
  29.         <!-- 文件类型 -->  
  30.         <param name="contentType"> application/vnd.ms-excel</param>  
  31.         <!-- excelStream 与对应action中的输入流的名字要一致 -->  
  32.         <param name" inputName"> excelStream</param>   
  33.         <!-- 文件名 与action中fileName一致 -->  
  34.         <param name="contentDisposition">attachment;filename=" ${fileName}.xls"</param>   
  35.         <param name="bufferSize">1024</param>   
  36.         </result>  
  37.         <result name="error">/WEB-INF/page/msg_error.jsp</result>   
  38.         </action>  
  39.     </package>  
  40.   
  41.   
  42. </struts>  

 

 

执行queryExport这acion 并设置属性包括操作流,文件名,文件类型等。具体见struts.xml的注释

 

QueryExportAction.java

        此action主要用于返回相应数据并通过流写入到新创建的Excel中,具体操作Excel代码如下:

 

  1. package com.ywjava.office.action;  
  2.   
  3. import java.io.ByteArrayInputStream;  
  • import java.io.ByteArrayOutputStream;  
  • import java.io.InputStream;  
  • import java.util.Calendar;  
  • import java.util.HashMap;  
  • import java.util.Iterator;  
  • import java.util.List;  
  •   
  • 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.opensymphony.xwork2.ActionContext;  
  • import com.opensymphony.xwork2.ActionSupport;  
  • import com.ywjava.office.domain.User;  
  • import com.ywjava.office.service.UserService;  
  • import com.ywjava.office.service.UserServiceImpl;  
  • import com.ywjava.office.utils.ExportTable;  
  •   
  • public class QueryExportAction extends ActionSupport {  
  •     private static final String EXPORT = "export";  
  •     private static final String QUERY = "query";  
  •     private String act;  
  •     private List<User> userInfos;  
  •     private UserService us = new UserServiceImpl();  
  •     private HashMap allParamsMap;  
  •     private String qry_param_prefix = "pram_";  
  •     // 这个输入流对应上面struts.xml中配置的那个excelStream,两者必须一致   
  •     private InputStream excelStream;  
  •   
  •     private String fileName; //文件名   
  •   
  •     public String execute() throws Exception {  
  •         //获取查询条件    
  •         allParamsMap = new HashMap();  
  •         ActionContext ctx = ActionContext.getContext();  
  •         String qryParamPrefix = qry_param_prefix.toUpperCase();  
  •         Iterator it = ctx.getParameters().keySet().iterator();  
  •         while (it.hasNext()) {  
  •             String keyName = (String) it.next();  
  •             if (keyName.toUpperCase().startsWith(qryParamPrefix)) {  
  •                 String[] vals = (String[]) (ctx.getParameters().get(keyName));  
  •                 if (vals != null && vals.length > 0) {  
  •                     allParamsMap.put(keyName, vals[0]); // name,value   
  •                 }  
  •             }  
  •         }  
  •         if (EXPORT.equals(act)) {  
  •             doExport(allParamsMap); // 根据查询条件 export    
  •         } else if (QUERY.equals(act)) {  
  •             doQuery(allParamsMap); // query   
  •         }  
  •   
  •         return SUCCESS;  
  •     }  
  •   
  •     /** 
  •      * 导出方法 
  •      *  
  •      * @return 
  •      * @throws Exception 
  •      */  
  •     @SuppressWarnings("unchecked")  
  •     private String doExport(HashMap paramsMap) throws Exception {  
  •         userInfos = us.exportUserInfo(allParamsMap); //获取符合条件的信息   
  •         if (userInfos == null) {  
  •             return ERROR;  
  •         }  
  •   
  •         else {  
  •             HSSFWorkbook workbook = this.getWorkbook(userInfos);   
  •             if (workbook != null) {  
  •                 Calendar c = Calendar.getInstance();  
  •                 int year = c.get(Calendar.YEAR);  
  •                 int month = c.get(Calendar.MONTH) + 1;  
  •                 String month_ = new String("" + month);  
  •                 if (month < 10) {  
  •                     month_ = "0" + month;  
  •                 }  
  •                 int day = c.get(Calendar.DAY_OF_MONTH);  
  •                 String day_ = new String("" + day);  
  •                 if (day < 10) {  
  •                     day_ = "0" + day;  
  •                 }  
  •                 this.workbook2InputStream(workbook, year + "-" + month_ + "-"  
  •                         + day_ + "");  
  •                 return SUCCESS;  
  •             } else {  
  •                 return ERROR;  
  •             }  
  •   
  •         }  
  •     }  
  •   
  •     /** 
  •      * 条件查询 
  •      *  
  •      * @return 
  •      */  
  •     public String doQuery(HashMap paramsMap) {  
  •         userInfos = us.getAllUser(paramsMap);  
  •         if (userInfos == null) {  
  •             return ERROR;  
  •         }  
  •   
  •         return SUCCESS;  
  •     }  
  •   
  •     public String getAct() {  
  •         return act;  
  •     }  
  •   
  •     public InputStream getExcelStream() {  
  •         return excelStream;  
  •     }  
  •   
  •     public String getFileName() {  
  •         return fileName;  
  •     }  
  •   
  •     public UserService getUs() {  
  •         return us;  
  •     }  
  •   
  •     public List<User> getUserInfos() {  
  •         return userInfos;  
  •     }  
  •     /** 
  •      * 创建一个excel文件。 
  •      * @param list 
  •      * @return 
  •      * @throws Exception 
  •      */  
  •     private HSSFWorkbook getWorkbook(List<User> list) throws Exception {  
  •         HSSFWorkbook workbook = new HSSFWorkbook(); // 创建工作表   
  •         HSSFCellStyle style = workbook.createCellStyle();  
  •         style.setAlignment(HSSFCellStyle.VERTICAL_CENTER);  
  •         style.setAlignment(HSSFCellStyle.ALIGN_CENTER);  
  •         HSSFSheet sheet = workbook.createSheet("sheet1"); // 创建表单   
  •         HSSFRow row = sheet.createRow(0); // 创建第一行 title   
  •         HSSFCell cell = null;  
  •         for (int i = 0; i < ExportTable.columnNames.length; i++) {  
  •             cell = row.createCell(i);  
  •             cell.setCellValue(ExportTable.columnNames[i]);  
  •             cell.setCellStyle(style);  
  •         }  
  •         // creatExportData   
  •   
  •         for (int i = 0; i < userInfos.size(); i++) {  
  •             row = sheet.createRow(i + 1);//   
  •             cell = row.createCell(0);  
  •             cell.setCellValue(userInfos.get(i).getId());  
  •             cell = row.createCell(1);  
  •             cell.setCellValue(userInfos.get(i).getName());  
  •             cell = row.createCell(2);  
  •             cell.setCellValue(userInfos.get(i).getAge());  
  •             cell = row.createCell(3);  
  •             cell.setCellValue(userInfos.get(i).getAddress());  
  •   
  •         }  
  •         return workbook;  
  •     }  
  •   
  •     public void setAct(String act) {  
  •         this.act = act;  
  •     }  
  •   
  •     public void setExcelStream(InputStream excelStream) {  
  •         this.excelStream = excelStream;  
  •     }  
  •   
  •     public void setFileName(String fileName) {  
  •         this.fileName = fileName;  
  •     }  
  •   
  •     public void setUs(UserService us) {  
  •         this.us = us;  
  •     }  
  •   
  •     public void setUserInfos(List<User> userInfos) {  
  •         this.userInfos = userInfos;  
  •     }  
  •         /* 
  •          * 写入流中 
  •          */  
  •     public void workbook2InputStream(HSSFWorkbook workbook, String fileName)  
  •             throws Exception {  
  •         this.fileName = fileName; // 设置文件名   
  •         ByteArrayOutputStream baos = new ByteArrayOutputStream();  
  •         workbook.write(baos);  
  •         baos.flush();  
  •         byte[] aa = baos.toByteArray();  
  •         excelStream = new ByteArrayInputStream(aa, 0, aa.length);  
  •         baos.close();  
  •   
  •     }  
  • }  
posted on 2013-12-14 15:08  wzh123  阅读(503)  评论(0编辑  收藏  举报