EXCEL导入数据库及数据库数据导出到EXCEL

 主要涉及内容及技术: 
  javaexcel api 
  jasonreport及编辑工具ireport和数据库技术。 
导入及导出EXCEL解决思路: 
  使用javaexcel api导入普通的EXCEL表格,就是没有合并单元格的规范数据,如果导出有规则的EXCEL也使用JAVAEXECEL API,对中文支持比较好。 
  如果要导出报表可打印的EXCEL,使用ireport为工具图形化画出报表,并使用jasonreprt控制导出,展示给客户端。 
  主要代码有: 
  连接数据库的方法: 

Java代码   收藏代码
  1. import java.sql.Connection;     
  2. import java.sql.ResultSet;     
  3. import java.sql.SQLException;     
  4. import java.sql.Statement;     
  5. import java.util.Hashtable;     
  6. import java.util.Vector;     
  7.      
  8. import org.apache.log4j.Logger;     
  9.      
  10. public class DBOperate {        
  11.   
  12.          
  13.     /**   
  14.      * 得到sequence的nextval   
  15.      * @param sequenceName    
  16.      * @return   
  17.      */     
  18.     public static String getSequence(String sequenceName) {     
  19.         String nextval = "";     
  20.         if(sequenceName == null || "".equals(sequenceName)) {     
  21.             System.out.println("sequenceName name is null!");                
  22.             return null;     
  23.         } else {     
  24.             sequenceName = sequenceName.toUpperCase();               
  25.             String sql = "select " + sequenceName + ".nextval nextid from user_sequences where sequence_name = '"      
  26.                        + sequenceName + "'";     
  27.                  
  28.             Statement stmt = null;     
  29.             Connection conn = null;     
  30.             ResultSet rs = null;     
  31.                  
  32.             try {     
  33.                 conn = TreatDB.getConnDB("");     
  34.                 if (conn != null) {     
  35.                     stmt = conn.createStatement();     
  36.                     rs = stmt.executeQuery(sql);     
  37.                          
  38.                     if(rs != null) {     
  39.                       while(rs.next()) {     
  40.                         nextval = rs.getString("nextid");                            
  41.                       }     
  42.                     }     
  43.                 }     
  44.             } catch (SQLException e) {     
  45.                 System.out.println("SQLException : " + e);     
  46.             } finally {     
  47.                 try {     
  48.                     if(rs != null) rs.close();     
  49.                     if(stmt != null) stmt.close();     
  50.                     if(conn != null) conn.close();     
  51.                 } catch (SQLException e) {     
  52.                     // TODO Auto-generated catch block                       
  53.                 }     
  54.             }     
  55.             return nextval;     
  56.         }     
  57.     }     
  58. /**   
  59.      * 一个插入、更新数据表的通用方法,传入一个sql脚本   
  60.      * @param sql :要进行操作的脚本   
  61.      * @return :发生变化的条数   
  62.      */     
  63.     public static int updateSql(String sql) {     
  64.         String dbName = "";     
  65.         Connection conn = null;     
  66.         Statement stmt = null;     
  67.         int result = 0;     
  68.         try {     
  69.             conn = TreatDB.getConnDB(dbName);     
  70.             if (conn != null) {     
  71.                 stmt = conn.createStatement();     
  72.                 //logger.info(sql);     
  73.                 result = stmt.executeUpdate(sql);                    
  74.                 conn.commit();     
  75.             }     
  76.      
  77.         } catch (SQLException e) {     
  78.             try {     
  79.                 conn.rollback();     
  80.             } catch (SQLException e1) {     
  81.                 System.out.println("update sql error: "+e);     
  82.                      
  83.             }                
  84.             System.out.println("update sql error: "+e);     
  85.             System.out.println("sql: " + sql);               
  86.         } finally {     
  87.             try {     
  88.                 if (stmt != null)     
  89.                     stmt.close();     
  90.                 if (conn != null)     
  91.                     conn.close();     
  92.             } catch (Exception ex) {     
  93.                 //do nothing;     
  94.             }     
  95.      
  96.         }     
  97.         return result;     
  98.     }     
  99.          
  100. }   


-------------------------------------------------------------------- 
导入EXCEL的程序代码: 
Java代码   收藏代码
  1. /**   
  2.      * 将Excel文件中的数据添加到数据库中   
  3.      * 新的监理信息 modify by heweiya   
  4.      *    
  5.      * @param xlsFile,Excel文件   
  6.      * @return   
  7.      */     
  8.     public String addJLXlsForm(InputStream is) {     
  9.              
  10.         String errStr = "";     
  11.         String result = "";          
  12.      
  13.         try {                
  14.             Workbook rwb = Workbook.getWorkbook(is);     
  15.             // Workbook rwb = Workbook.getWorkbook(new File(filePath+fileName));     
  16.             // 获取第一张Sheet表     
  17.             Sheet sheet = rwb.getSheet(0);     
  18.             // 获取总列数     
  19.             int rsColumns = sheet.getColumns();     
  20.             System.out.println("rsColumns = " + rsColumns);     
  21.                  
  22.             // 获取总行数     
  23.             int rsRows = sheet.getRows();     
  24.             System.out.println("rsRows = " + rsRows);     
  25.                  
  26.             if (rsColumns < 19) {     
  27.                 errStr = "错误原因:字段不全。";     
  28.                 vErr.addElement(errStr);     
  29.             }     
  30.                  
  31.             int i = 0;     
  32.             int startRows = 1;     
  33.             int startColumn = 0;     
  34.             while (startRows < rsRows) {     
  35.                 Hashtable ht = new Hashtable();     
  36.                      
  37.                 String zj_id = DBOperate.getSequence("S_JIANLI");            
  38.      
  39.                      
  40.                 Cell tmp = sheet.getCell(0,startRows);                       
  41.                 String sfzh = tmp.getContents();         
  42.                      
  43.                 tmp = sheet.getCell(1,startRows);                        
  44.                 String issueDate = tmp.getContents();                    
  45.                 String issueDate_new = "";     
  46.                 if(issueDate != null && issueDate.length()>=6) issueDate_new = issueDate.substring(6) + issueDate.substring(3,5) + issueDate.substring(0,2);     
  47.                      
  48.                 tmp = sheet.getCell(2,startRows);                        
  49.                 String approveDate = tmp.getContents();                  
  50.                 String approve_date_new = "";     
  51.                 if(approveDate != null && approveDate.length()>=6) approve_date_new = approveDate.substring(6) + approveDate.substring(3,5) + approveDate.substring(0,2);     
  52.                  
  53.                 tmp = sheet.getCell(3,startRows);                        
  54.                 String cerNo = tmp.getContents();     
  55.                      
  56.                 tmp = sheet.getCell(4,startRows);                        
  57.                 String jianliMajor = tmp.getContents();                  
  58.      
  59.                 tmp = sheet.getCell(5,startRows);                        
  60.                 String department = tmp.getContents();     
  61.                      
  62.                 tmp = sheet.getCell(6,startRows);                        
  63.                 String jianliName = tmp.getContents();     
  64.                  
  65.                 tmp = sheet.getCell(7,startRows);                        
  66.                 String jianliSex = tmp.getContents();                            
  67.                      
  68.                 //毕业院校     
  69.                 tmp = sheet.getCell(8,startRows);                        
  70.                 String degree = tmp.getContents();     
  71.                  
  72.                 //毕业时间     
  73.                 tmp = sheet.getCell(9,startRows);                        
  74.                 String cooleage = tmp.getContents();     
  75.                  
  76.                 //所学专业     
  77.                 tmp = sheet.getCell(10,startRows);                       
  78.                 String company = tmp.getContents();     
  79.                  
  80.                 //职务     
  81.                 tmp = sheet.getCell(11,startRows);                       
  82.                 String tech_post = tmp.getContents();                    
  83.                      
  84. //              工作单位     
  85.                 tmp = sheet.getCell(12,startRows);                       
  86.                 String address = tmp.getContents();                  
  87.                      
  88. //              职称     
  89.                 tmp = sheet.getCell(13,startRows);                       
  90.                 String postcode = tmp.getContents();                     
  91.                      
  92.                 tmp = sheet.getCell(14,startRows);                       
  93.                 String jianliTel = tmp.getContents();     
  94.                      
  95.                 tmp = sheet.getCell(15,startRows);                       
  96.                 String mobile = tmp.getContents();     
  97.                      
  98.                 tmp = sheet.getCell(16,startRows);                       
  99.                 String email = tmp.getContents();     
  100.                      
  101.                 tmp = sheet.getCell(17,startRows);                       
  102.                 String birthday = tmp.getContents();                     
  103.                 String birthday_new = "";     
  104.                 if(birthday != null && birthday.length()>=6) birthday_new = birthday.substring(6) + birthday.substring(3,5) + birthday.substring(0,2);     
  105.                      
  106.                      
  107.                 tmp = sheet.getCell(18,startRows);                       
  108.                 String jianli_type = tmp.getContents();      
  109.                 //加入密码 modify by heweiya 2007/05/17     
  110.                 String sql = "insert into jianli values('" + zj_id + "', '" + sfzh + "', to_date('" + issueDate_new + "','yyyymmdd'),to_date('"     
  111.                    + approve_date_new + "','yyyymmdd'),'" + cerNo + "','" + jianliMajor + "','" + department + "','"     
  112.                    + jianliName + "','" + jianliSex + "','" + degree + "','" + cooleage + "','"      
  113.                    + company + "','" + tech_post + "','" + address + "','" + postcode + "','" + jianliTel      
  114.                    + "','" + mobile + "','" + email + "',to_date('" + birthday_new + "','yyyymmdd'),'" + jianli_type  + "',null,null,null,null,"+sfzh.substring(010)+",null,null,null,null,null)";     
  115.                      
  116.                 int a = DBOperate.updateSql(sql);     
  117.                      
  118.                 System.out.println("成功导入第"+startRows+"条");           
  119.                 if (a == 0) {     
  120.                     errStr = errStr + "添加失败:库中已有此记录,或有值不符合库中设定的字段属性!";     
  121.                 } else if (a == 1) {     
  122.                     result = "添加成功";     
  123.                 } else {     
  124.                     errStr = errStr + "添加失败:连接数据库失败";     
  125.                 }     
  126.                          
  127.                      
  128.      
  129.                 if (!"".equals(errStr)) {     
  130.                     vErr.addElement("导入:" + "【" + startRows + "】" + "<br>(错误原因:" + errStr);     
  131.                     errStr += "导入:" + "【" + startRows + "】" + "<br>(关键字段为:姓名:"+jianliName+",身份证号为:"+sfzh+",监理证书号为:"+cerNo+")<br>";     
  132.                 } else {     
  133.                     vOk.add(ht);     
  134.                 }     
  135.      
  136.                 startRows++;     
  137.             }     
  138.                  
  139.             rwb.close();     
  140.             result = "成功导入:" + vOk.size()+"条记录。<br> 错误导入: " + vErr.size()+"条记录,错误记录及原因如下:<br>"+errStr;     
  141.             System.out.println("vOK.size() = " + vOk.size());     
  142.             System.out.println("VErr.size() = " + vErr.size());     
  143.             return result;     
  144.         } catch (Exception e) {     
  145.             result = "在导入的过程当中发生了错误,其中错误的原因是:" + e.toString();               
  146.             return result;     
  147.         }     
  148.     }     

------------------------------------------------------------------------------ 
导出报表的代码: 
Java代码   收藏代码
  1. /**   
  2.  *    
  3.  * 导出报表   
  4.  *    
  5.  * @param   
  6.  * @return   
  7.  * @throws   
  8.  */     
  9. public ActionForward ExportXLS(ActionMapping mapping, ActionForm form,     
  10.         HttpServletRequest request, HttpServletResponse response)     
  11.         throws Exception {     
  12.     HttpSession session = request.getSession();     
  13.     String CerNo = (String) session.getAttribute("CerNo");// 登录名     
  14.     String JianliName = (String) session.getAttribute("JianliName");// 角色ID     
  15.     if (CerNo == null || JianliName == null) {     
  16.         return mapping.findForward("Fail");     
  17.     }     
  18.     File business_rpt = new File(getServlet().getServletConfig()     
  19.             .getServletContext().getRealPath("/report/water_jianli.jasper"));     
  20.     JasperPrint jasperPrint = null;     
  21.      
  22.     Map parameters = new HashMap();     
  23.     Jianli jianli = personalDAO.GetJianli(CerNo);     
  24.      
  25.     ReportModel report_user = new ReportModel();     
  26.     report_user.setCol1(jianli.getJianliName());// 姓名     
  27.     report_user.setCol2(jianli.getJianliSex());// 性别     
  28.     report_user.setCol3(jianli.getDegree());// 学历     
  29.     report_user.setCol4("'" + jianli.getSfzh());// 身份证     
  30.     report_user.setCol5(jianli.getTechPost());// 职称     
  31.     report_user.setCol6(jianli.getCerNo());// 证书编号     
  32.     report_user.setCol7(jianli.getJianliMajor());// 监理专业     
  33.     if (jianli.getOrgs() != null) {     
  34.         report_user.setCol8(jianli.getOrgs().getOrgName());// 隶属单位     
  35.     }     
  36.     report_user.setCol10(jianli.getAddress());     
  37.     report_user.setCol11(jianli.getJianliTel());     
  38.     /**   
  39.      * 加入简历的东东   
  40.      */     
  41.     List Ljianli = assistDAO.GetEngineerAssist(CerNo);     
  42.     if (Ljianli != null) {     
  43.         for (int i = 0; i < Ljianli.size(); i++) {     
  44.             Assistant assist = (Assistant) Ljianli.get(i);     
  45.             String begindate = "";     
  46.             String enddate = "";     
  47.             SimpleDateFormat sfDate = new SimpleDateFormat("yyyy/MM/dd");     
  48.             if (assist.getBegindate() != null) {     
  49.                 begindate = sfDate.format(assist.getBegindate());     
  50.             }     
  51.             if (assist.getEnddate() != null) {     
  52.                 enddate = sfDate.format(assist.getEnddate());     
  53.             }        
  54.             String deptname = (assist.getAtdeptname() == null)?"":assist.getAtdeptname();     
  55.             String zewu = (assist.getAssistname() == null)?"":assist.getAssistname();     
  56.             String huihua = "开始日期为:" + begindate + ",结束日期为:" + enddate     
  57.                     + ",所在工作单位"+deptname+",担任职务为:" + zewu+"。";     
  58.             if (assist.getOther() != null){     
  59.          &nbs  
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值