Java 讀寫 Excel 文件

一、寫入 Excel 文件:

  1. /**  
  2.  *   
  3.  * <p>Discription:[寫入Excel]</p>  
  4.  * @param fileName  
  5.  * @param list  
  6.  * @author:[LJ]  
  7.  * @update:[2012-4-9] [LJ][創建]  
  8.  */ 
  9. public static void writeExcel(String fileName, List list)  
  10. {  
  11.     WritableWorkbook wwb = null;  
  12.     try 
  13.     {  
  14.         //首先使用Workbook類的工廠方法創建一個可寫入的工作薄(Workbook)對象  
  15.         wwb = Workbook.createWorkbook(new File(fileName));  
  16.     }  
  17.     catch (IOException e)  
  18.     {  
  19.         System.out.println("創建工作簿失敗!");  
  20.     }  
  21.     if(wwb != null)  
  22.     {  
  23.         //創建一個可寫入的工作表  
  24.         //Workbook的createSheet方法有兩個參數,第一個是工作表的名稱,第二個是工作表在工作薄中的位置  
  25.         WritableSheet ws = wwb.createSheet("mySheet1"0);               
  26.           
  27.         for(int i = 0,n = list.size();i < n;i++)  
  28.         {  
  29.             EmpBean emp = (EmpBean)list.get(i);  
  30.             //這裏需要注意的是,在Excel中,第一個參數表示列,第二個表示行,第三個表示單元格內容  
  31.             Label labelEmpNo    = new Label(0, i, emp.getEmpNo());  
  32.             Label labelEname    = new Label(1, i, emp.getEname());  
  33.             Label labelJob      = new Label(2, i, emp.getJob());  
  34.             Label labelMgr      = new Label(3, i, emp.getMgr());  
  35.             Label labelHireDate = new Label(4, i, emp.getHireDate());  
  36.             Label labelSal      = new Label(5, i, emp.getSal());  
  37.             Label labelComm     = new Label(6, i, emp.getComm());  
  38.             Label labelDeptNo   = new Label(6, i, emp.getDeptNo());  
  39.  
  40.             try   
  41.             {  
  42.                //將生成的單元格添加到工作表中  
  43.                ws.addCell(labelEmpNo);  
  44.                ws.addCell(labelEname);  
  45.                ws.addCell(labelJob);  
  46.                ws.addCell(labelMgr);  
  47.                ws.addCell(labelHireDate);  
  48.                ws.addCell(labelSal);  
  49.                ws.addCell(labelComm);  
  50.                ws.addCell(labelDeptNo);  
  51.             }   
  52.             catch (RowsExceededException e)   
  53.             {  
  54.                 e.printStackTrace();  
  55.             }   
  56.             catch (WriteException e)   
  57.             {  
  58.                 e.printStackTrace();  
  59.             }  
  60.         }           
  61.       
  62.         try   
  63.         {  
  64.             //從內存中寫入文件中  
  65.             wwb.write();  
  66.             //關閉資源,釋放內存  
  67.             wwb.close();  
  68.          }   
  69.         catch (IOException e)   
  70.         {  
  71.             e.printStackTrace();  
  72.         }   
  73.         catch (WriteException e)   
  74.         {  
  75.             e.printStackTrace();  
  76.         }  
  77.     }  

二、讀取 Excel 文件:

  1. /**  
  2.  *   
  3.  * <p>Discription:[讀取Excel]</p>  
  4.  * @param file  
  5.  * @return  
  6.  * @author:[LJ]  
  7.  * @update:[2012-4-9] [LJ][創建]  
  8.  */ 
  9. public static String readExcel(File file)  
  10. {  
  11.     StringBuffer sb = new StringBuffer();          
  12.     Workbook wb = null;  
  13.     try   
  14.     {  
  15.         //構造Workbook(工作薄)對象  
  16.         wb=Workbook.getWorkbook(file);  
  17.     }   
  18.     catch (BiffException e)   
  19.     {  
  20.         e.printStackTrace();  
  21.     }   
  22.     catch (IOException e)   
  23.     {  
  24.         e.printStackTrace();  
  25.     }  
  26.       
  27.     if(wb==null)  
  28.     {  
  29.         return null;  
  30.     }  
  31.       
  32.     //獲得了Workbook對象之後,就可以通過它得到Sheet(工作表)對象了  
  33.     Sheet[] sheet = wb.getSheets();  
  34.       
  35.      if(sheet!=null&&sheet.length>0)  
  36.      {  
  37.          //對每個工作表進行循環  
  38.          for(int i=0;i<sheet.length;i++)  
  39.          {  
  40.              //得到當前工作表的行數  
  41.              int rowNum = sheet[i].getRows();  
  42.              for(int j=0;j<rowNum;j++)  
  43.              {  
  44.                  //得到當前行的所有單元格  
  45.                  Cell[] cells = sheet[i].getRow(j);  
  46.                  if(cells!=null&&cells.length>0)  
  47.                  {  
  48.                      //對每個單元格進行循環  
  49.                      for(int k=0;k<cells.length;k++)  
  50.                      {  
  51.                          //讀取當前單元格的值  
  52.                          String cellValue = cells[k].getContents();  
  53.                          sb.append(cellValue+",");  
  54.                     }  
  55.                 }  
  56.                 sb.deleteCharAt(sb.length()-1);  
  57.                 sb.append(";");  
  58.             }  
  59.              sb.deleteCharAt(sb.length()-1);  
  60.             sb.append("。");  
  61.         }  
  62.     }  
  63.     //最後關閉資源,釋放內存  
  64.     wb.close();          
  65.     return sb.toString();  

三、準備數據:

  1. /**  
  2.  *   
  3.  * <p>Discription:[獲取數據]</p>  
  4.  * @return  
  5.  * @author:[LJ]  
  6.  * @update:[2012-4-9] [LJ][創建]  
  7.  */ 
  8. public static List<EmpBean> getEmp()  
  9. {  
  10.     Connection conn = null;  
  11.     Statement stmt = null;  
  12.     ResultSet rs = null;  
  13.     String sql = "select * from emp";  
  14.     List<EmpBean> empList = new ArrayList<EmpBean>();  
  15.     try 
  16.     {  
  17.         Class.forName("oracle.jdbc.driver.OracleDriver");  
  18.         conn = DriverManager.getConnection("jdbc:oracle:thin:@127.0.0.1:1521:orcl","scott","tiger");  
  19.         stmt = conn.createStatement();  
  20.  
  21.         rs = stmt.executeQuery(sql);  
  22.         //獲取字段名稱  
  23.         ResultSetMetaData metaData  = rs.getMetaData();  
  24.         for (int i = 1; i <= metaData.getColumnCount(); ++i)   
  25.         {                  
  26.             EmpBean emp = new EmpBean();  
  27.             emp.setEmpNo(metaData.getColumnName(i));  
  28.             emp.setEname(metaData.getColumnName(++i));  
  29.             emp.setJob(metaData.getColumnName(++i));  
  30.             emp.setMgr(metaData.getColumnName(++i));  
  31.             emp.setHireDate(metaData.getColumnName(++i));  
  32.             emp.setSal(metaData.getColumnName(++i));  
  33.             emp.setComm(metaData.getColumnName(++i));  
  34.             emp.setDeptNo(metaData.getColumnName(++i));  
  35.             empList.add(emp);  
  36.             //StringBuffer str = new StringBuffer();  
  37.             //獲取字段類型名稱和精度  
  38.             //str.append(metaData.getColumnTypeName(i)+"("+metaData.getPrecision(i)+")");  
  39.  
  40.         }   
  41.         SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");  
  42.         while(rs.next())  
  43.         {                 
  44.             EmpBean emp = new EmpBean();  
  45.             emp.setEmpNo(rs.getString("EMPNO"));  
  46.             emp.setEname(rs.getString("ENAME"));  
  47.             emp.setJob(rs.getString("JOB"));  
  48.             emp.setMgr(rs.getString("MGR"));                  
  49.             emp.setHireDate(sdf.format(rs.getDate("HIREDATE")));  
  50.             emp.setSal(rs.getString("SAL"));  
  51.             emp.setComm(rs.getString("COMM"));  
  52.             emp.setDeptNo(rs.getString("DEPTNO"));  
  53.             empList.add(emp);  
  54.         }  
  55.     }  
  56.     catch (Exception e)  
  57.     {  
  58.         System.out.println("查詢失敗!");  
  59.     }  
  60.     finally 
  61.     {  
  62.         try 
  63.         {  
  64.             if(rs!=null)  
  65.             {  
  66.                 rs.close();  
  67.             }  
  68.             if(stmt!=null)  
  69.             {  
  70.                 stmt.close();  
  71.             }  
  72.             if(conn!=null)  
  73.             {  
  74.                 conn.close();  
  75.             }  
  76.         }  
  77.         catch (SQLException e)  
  78.         {  
  79.             System.out.println("關閉失敗!");  
  80.         }  
  81.     }  
  82.     return empList;  

四、測試主函數:

  1. /**  
  2.  * <p>Discription:[main函數]</p>  
  3.  * @param args  
  4.  * @author:[LJ]  
  5.  * @update:[2012-4-7] [LJ][創建]  
  6.  */ 
  7.  
  8. public static void main(String[] args)  
  9. {  
  10.     //獲取數據  
  11.     List<EmpBean> list = getEmp();  
  12.     //將數據寫入Excel文件  
  13.     writeExcel("D:\\myExcel.xls", list);  
  14.     //讀出Excel文件的內容  
  15.     readExcel(new File("D:\\myExcel.xls"));  

PS :  讀寫 Excel 文件需要引入 jxl.jar 包,下載地址:
http://www.andykhan.com/jexcelapi/download.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章