分享

excel导入导出通用

 hehffyy 2011-07-18
Java代码  收藏代码
  1.   

 show.isp文件

Java代码  收藏代码
  1.  <%@ page contentType="text/html;charset=gb2312" %>  
  2. <%@ page language="java" import="java.util.*" pageEncoding="gb2312"%>  
  3.   
  4. <%@ taglib uri="http://struts./tags-bean" prefix="bean" %>  
  5. <%@ taglib uri="http://struts./tags-html" prefix="html" %>  
  6. <%@ taglib uri="http://struts./tags-logic" prefix="logic" %>  
  7. <%@ taglib uri="http://struts./tags-tiles" prefix="tiles" %>  
  8. <%@ taglib uri="/WEB-INF/c.tld" prefix="c" %>  
  9. <script>   
  10. function selectAll(obj)   
  11. {   
  12. for(var i = 0;i<obj.elements.length;i++)   
  13. if(obj.elements[i].type == "checkbox")   
  14. obj.elements[i].checked = true;   
  15. }   
  16. function selectOther(obj)   
  17. {   
  18. for(var i = 0;i<obj.elements.length;i++)   
  19. if(obj.elements[i].type == "checkbox" )   
  20. {   
  21. if(!obj.elements[i].checked)   
  22. obj.elements[i].checked = true;   
  23. else   
  24. obj.elements[i].checked = false;   
  25. }   
  26. }   
  27. </script>  
  28. <%  
  29.              int pageno = ((Integer)request.getAttribute("pageno")).intValue();  
  30.              int totalpage = ((Integer)request.getAttribute("totalpage")).intValue();  
  31.          %>  
  32. <html>  
  33.   
  34.     <body>  
  35.            
  36.         <form action="loadfile.do" method="post" enctype="multipart/form-data">  
  37.             <table><tr><td><input type="file" name="file" size="20"></td><td>  
  38.             <input type="submit" value="上传"></td></tr>  
  39.         </form>  
  40.         <form action="<%=request.getContextPath()%>/address.do?method=exportExcel"  
  41.             method="post" >  
  42.             <table><tr><td><input type="submit" name="import"  value="IMPORT"></td><td>  
  43.              </td></tr>  
  44.         </form>  
  45.         </table>  
  46.          
  47.     </body>  
  48. </html>  

 

 

调用 loadfile.jsp文件

Java代码  收藏代码
  1. <%@ page contentType="text/html; charset=GBK"%>  
  2. <%@ page import="java.util.*"%>  
  3. <%@ page import="com.jspsmart.upload.*"%>  
  4. <%  
  5. //@ page import="com.suntek.devmanager.web.SysParam"  
  6. %>  
  7. <%@ page import="java.io.*"%>  
  8. <jsp:useBean id="smartUpload" scope="page"  
  9.     class="com.jspsmart.upload.SmartUpload" />  
  10. <%  
  11.     request.getSession().removeAttribute("FileInputStream");  
  12.     String contract_id = "", add_flag = "";  
  13.     try {  
  14.         //    SmartUpload smartUpload = new SmartUpload();  
  15.         smartUpload.initialize(pageContext);  
  16.         //最大上传文件小于四兆  
  17.         smartUpload.setTotalMaxFileSize(4096000);  
  18.         //上载文件  
  19.         smartUpload.upload();  
  20.         //取得上载的文件  
  21.   
  22.         com.jspsmart.upload.File lo_File = smartUpload.getFiles().getFile(0);  
  23.         byte[] fileContent = new byte[(int) lo_File.getSize()];  
  24.         for (int k = 0; k < (int) lo_File.getSize(); k++) {  
  25.             fileContent[k] = lo_File.getBinaryData(k);  
  26.         }  
  27.         InputStream fs = null;  
  28.         if (!lo_File.isMissing()) {  
  29.             //取得上载的文件的文件名  
  30.             fs = new ByteArrayInputStream(fileContent);  
  31.             //将文件写到数据库中  
  32.         }  
  33.       
  34.         request.getSession().setAttribute("InputStream", fs);  
  35.         //得到文件名  
  36.     } catch (Exception e) {  
  37.         e.printStackTrace();  
  38.         return;  
  39.     }  
  40. %>  
  41. <html>  
  42.     <head>  
  43.           
  44.         <script language="javascript">  
  45. function Window_Onload()  
  46. {  
  47.   document.all.manager.submit();  
  48.  // window.returnValue = "true";  
  49.  // top.close();  
  50. }  
  51. </script>  
  52.         <title>有问题请和我联系</title>  
  53.     </head>  
  54.     <body leftmargin="0" topmargin="0" class="DialogOuter"  
  55.         onload="return Window_Onload();">  
  56.         <form action="<%=request.getContextPath()%>/address.do?method=addExcel"  
  57.                     method="post" name="manager">  
  58.         </form>  
  59.         <br>  
  60.         <br>  
  61.         <br>  
  62.         <br>  
  63.         <div align="center">  
  64.             系统正在上传数据,请稍候!!  
  65.         </div>  
  66.     </body>  
  67. </html>  

 

 

 action文件

Java代码  收藏代码
  1.    
  2. package com.yourcompany.struts.action;  
  3.   
  4. import java.io.FileInputStream;  
  5. import java.io.IOException;  
  6. import java.io.InputStream;  
  7. import java.sql.Connection;  
  8. import java.util.ArrayList;  
  9. import java.util.List;  
  10.   
  11. import javax.servlet.http.HttpServletRequest;  
  12. import javax.servlet.http.HttpServletResponse;  
  13.   
  14. import jxl.Cell;  
  15. import jxl.Sheet;  
  16. import jxl.Workbook;  
  17. import jxl.write.Label;  
  18. import jxl.write.WritableSheet;  
  19. import jxl.write.WritableWorkbook;  
  20.   
  21. import org.apache.struts.action.ActionForm;  
  22. import org.apache.struts.action.ActionForward;  
  23. import org.apache.struts.action.ActionMapping;  
  24. import org.apache.struts.actions.DispatchAction;  
  25. import org.jaxen.function.ext.LowerFunction;  
  26.   
  27. import com.dao.Service;  
  28. import com.db.Conn;  
  29. import com.tb.Factory.DaoFactory;  
  30. import com.tb.hibernate.Address;  
  31. import com.yourcompany.struts.form.AddressForm;  
  32.   
  33. /** 
  34.  * MyEclipse Struts Creation date: 05-16-2008 
  35.  *  
  36.  * XDoclet definition: 
  37.  *  
  38.  * @struts.action path="/address" name="addressForm" input="/form/address.jsp" 
  39.  *                scope="request" validate="true" 
  40.  */  
  41. public class AddressAction extends DispatchAction {  
  42.     /* 
  43.      * Generated Methods 
  44.      */  
  45.    
  46.        
  47.     public  ActionForward addExcel(ActionMapping mapping, ActionForm form,  
  48.             HttpServletRequest request, HttpServletResponse response) {  
  49.         //AddressForm addressForm = (AddressForm) form;  
  50.          try {  
  51.              InputStream is = (InputStream) request.getSession().getAttribute("InputStream");  
  52.              //InputStream is = new FileInputStream("c://Address.xls");  
  53.              Connection conn = Conn.Conn().getconn();  
  54.              Service.service().importexcel(is,conn, "ADDRESS",5);//  
  55.               
  56.         }catch (Exception e) {  
  57.             // TODO 自动生成 catch 块  
  58.             e.printStackTrace();  
  59.         }   
  60.            
  61.         return mapping.findForward("index");  
  62.     }  
  63.     public ActionForward exportExcel(ActionMapping mapping, ActionForm form,  
  64.             HttpServletRequest request, HttpServletResponse response) {  
  65.          Connection conn = Conn.Conn().getconn();  
  66.          response.reset();  
  67.          response.setCharacterEncoding("GBK");  
  68.          response.setContentType("Application/msexcel;charset=gbk");  
  69.          response.setHeader("Content-disposition","attachment; 导出数据.xls");  
  70.          WritableWorkbook book = null;  
  71.          try {  
  72.              book = Workbook.createWorkbook(response.getOutputStream());  
  73.              WritableSheet sheet = book.createSheet("数据"0);  
  74.                
  75.              Label label = new Label(11"1234");  
  76.              sheet.addCell(label);  
  77.                   
  78.              book.write();  
  79.              book.close();  
  80.         } catch (Exception e) {  
  81.             // TODO Auto-generated catch block  
  82.             e.printStackTrace();  
  83.         }  
  84.          // Service.service().exportexcel(conn, "ADDRESS");//  
  85.         return null;  
  86.     }  
  87. }  

 

调用的service文件

Java代码  收藏代码
  1. package com.dao;  
  2.   
  3. import java.io.InputStream;  
  4. import java.sql.Connection;  
  5. import java.sql.PreparedStatement;  
  6. import java.sql.ResultSet;  
  7. import java.sql.SQLException;  
  8. import java.sql.Statement;  
  9. import java.util.ArrayList;  
  10. import java.util.List;  
  11.   
  12. import jxl.Cell;  
  13. import jxl.Sheet;  
  14. import jxl.Workbook;  
  15.   
  16. import com.db.Conn;  
  17. import com.tb.hibernate.Address;  
  18.   
  19. /** 
  20.  * @author Administrator 
  21.  * 
  22.  */   
  23. /** 
  24.  * @author Administrator 
  25.  * 
  26.  */  
  27. public class Service {  
  28.     private static Service service = new Service();  
  29.     public static Service service(){  
  30.         if(service == null){  
  31.             return new Service();  
  32.         }else{  
  33.             return service;  
  34.         }  
  35.     }  
  36.     /** 
  37.      * @author Administrator 
  38.      *获得table 表的字段类型或者字段名 
  39.      *column_name,data_type 
  40.      */  
  41.    public List getTypeNameOrColumnName(Connection conn, String tableName,String arg){  
  42.        Statement ps = null;  
  43.        ResultSet rs = null;  
  44.        List<String> list = new ArrayList<String>();  
  45.        String sql="select "+arg+" from user_tab_columns where  table_name like '"+tableName+"'";  
  46.        try {  
  47.         ps = conn.createStatement();  
  48.         rs = ps.executeQuery(sql);  
  49.         while(rs.next()){  
  50.             list.add(rs.getString(arg));  
  51.         }  
  52.     } catch (SQLException e) {  
  53.         // TODO Auto-generated catch block  
  54.         e.printStackTrace();  
  55.     }  
  56.        return list;  
  57.    }  
  58.    /** 
  59.     * @author Administrator 
  60.     * 将导入的excle插入到table中 
  61.     */  
  62.    public boolean insertTable(Connection conn, String tableName,  List<String> list,int colNum){  
  63.         PreparedStatement ps = null;  
  64.          
  65.         try {  
  66.             String  columnName="";    
  67.             List<String> columnList = getTypeNameOrColumnName(conn,"ADDRESS","column_name");  
  68.             for(int i=0;i<colNum+1;i++){  
  69.                columnName += columnList.get(i);  
  70.                columnName +=",";  
  71.             }  
  72.             columnName = columnName.substring(0,columnName.length()-1);  
  73.             conn.setAutoCommit(false);  
  74.             for(int j=0; j< list.size();j++){  
  75.                 String sql="insert into  "+tableName+"("+columnName+") values(seq_a.nextval,"+list.get(j)+")";  
  76.                 ps = conn.prepareStatement(sql);  
  77.                 ps.addBatch();  
  78.                 if (j % 100 == 0 ) {  
  79.                     ps.executeBatch();  
  80.                     conn.commit();  
  81.                 }else{  
  82.                     ps.executeBatch();  
  83.                     conn.commit();  
  84.                 }  
  85.             }  
  86.             conn.setAutoCommit(true);  
  87.         }catch (Exception e) {  
  88.             // TODO: handle exception  
  89.              e.printStackTrace();  
  90.         }  
  91.        return true;  
  92.    }  
  93.      
  94.    /** 
  95.     *  
  96.     * @param is excel文件流 
  97.     * @param conn 数据连接 
  98.     * @param tableName 表名 
  99.     * @param colNum excel中数据列数 
  100.     */  
  101.    public void importexcel(InputStream is,Connection conn, String tableName, int colNum){  
  102.       try{  
  103.          jxl.Workbook rwb = Workbook.getWorkbook(is);  
  104.          Sheet[] sheets = rwb.getSheets(); //   
  105.          List<String> list = Service.service().getTypeNameOrColumnName(conn,tableName,"data_type");  
  106.          int nullCol = list.size()-colNum; //后面不用复制的项数  
  107.          List<String> listarray = new ArrayList<String>();  
  108.          for(int i=0; i<sheets.length; i++){  
  109.              Sheet sheet = sheets[i];  
  110.                 //k代表数据所在的行  
  111.                   for(int k=0; k<sheet.getRows(); k++){  
  112.                      Address address = new Address();  
  113.                      StringBuffer str = new StringBuffer();  
  114.                        for(int m=0;m<list.size()-nullCol;m++){  
  115.                         // for(int m=0;m<colNum;m++){  
  116.                            Cell  cel1= sheet.getCell(m,k);//列,行,   
  117.                            //将数据根据不同数据类型拼接为串  
  118.                            if(list.get(m+1).toUpperCase().indexOf("NUMBER")>-1 ||list.get(m+1).toUpperCase().indexOf("INT")>-1){//  
  119.                               if(!"".equals(cel1.getContents())){  
  120.                                 str.append(cel1.getContents());   
  121.                               }else{  
  122.                                   str.append(0);   
  123.                               }  
  124.                               //DATE、DATETIME、TIME、TIMESTAMP to_date('2002-02-28','yyyy-mm-dd')   
  125.                            }else if(list.get(m+1).toUpperCase().indexOf("DATE")>-1||list.get(m+1).toUpperCase().indexOf("TIMESTAMP")>-1  
  126.                                     ||list.get(m+1).toUpperCase().indexOf("DATETIME")>-1||list.get(m+1).toUpperCase().indexOf("TIME")>-1){  
  127.                                String strdate ="";  
  128.                                if(!"".equals(cel1.getContents())){  
  129.                                   strdate = "to_date('"+cel1.getContents()+"','yy-mm-dd')";  
  130.                                }  
  131.                                str.append(!"".equals(cel1.getContents())?strdate:"NULL");  
  132.                            }else{  
  133.                                str.append("'");  
  134.                                str.append(!"".equals(cel1.getContents())?cel1.getContents().trim():cel1.getContents());  
  135.                                str.append("'");  
  136.                            }  
  137.                            str.append(",");  
  138.                        }  
  139.                        listarray.add(str.toString().substring(0, str.toString().length()-1));  
  140.                  }  
  141.          }  
  142.          Service.service().insertTable(conn,tableName,listarray,colNum);  
  143.       }catch(Exception e){  
  144.           e.printStackTrace();  
  145.       }  
  146.    }  
  147. }  
  148.    

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多