java匯出資料庫的全部表到excel_java

來源:互聯網
上載者:User

本文執行個體為大家分享了java將某個資料庫的表全部匯出到excel中的方法,供大家參考,具體內容如下

第一步:如何用POI操作Excel

@Test public void createXls() throws Exception{  //聲明一個工作薄  HSSFWorkbook wb = new HSSFWorkbook();  //聲明表  HSSFSheet sheet = wb.createSheet("第一個表");  //聲明行  HSSFRow row = sheet.createRow(7);  //聲明列  HSSFCell cel = row.createCell(3);  //寫入資料  cel.setCellValue("你也好");    FileOutputStream fileOut = new FileOutputStream("d:/a/b.xls");  wb.write(fileOut);  fileOut.close(); }

第二步:匯出指定資料庫的所有表

分析:

       1:某個數資料庫有多少表,表名是什嗎?―――DataBaseMetadate.getMetadate().getTables(null,null,null,new String[]{Table});  - excel的檔案名稱。

  2:對每一個表進行select * 操作。 - 每一個sheet的名稱。

  3:分析表結構,rs.getMetadate(); ResultSetMedated

  4:多個列,列名是什麼.  - 欄位名就是sheet的第一行資訊。

  5:擷取每一行的資料 – 放到sheet第一行以後。

@Test public void export() throws Exception{  //聲明需要匯出的資料庫  String dbName = "focus";  //聲明book  HSSFWorkbook book = new HSSFWorkbook();  //擷取Connection,擷取db的中繼資料  Connection con = DataSourceUtils.getConn();  //聲明statemen  Statement st = con.createStatement();  //st.execute("use "+dbName);  DatabaseMetaData dmd = con.getMetaData();  //擷取資料庫有多少表  ResultSet rs = dmd.getTables(dbName,dbName,null,new String[]{"TABLE"});  //擷取所有表名 - 就是一個sheet  List<String> tables = new ArrayList<String>();  while(rs.next()){   String tableName = rs.getString("TABLE_NAME");   tables.add(tableName);  }  for(String tableName:tables){   HSSFSheet sheet = book.createSheet(tableName);   //聲明sql   String sql = "select * from "+dbName+"."+tableName;   //查詢資料   rs = st.executeQuery(sql);   //根據查詢的結果,分析結果集的中繼資料   ResultSetMetaData rsmd = rs.getMetaData();   //擷取這個查詢有多少行   int cols = rsmd.getColumnCount();   //擷取所有列名   //建立第一行   HSSFRow row = sheet.createRow(0);   for(int i=0;i<cols;i++){    String colName = rsmd.getColumnName(i+1);    //建立一個新的列    HSSFCell cell = row.createCell(i);    //寫入列名    cell.setCellValue(colName);   }   //遍曆資料   int index = 1;   while(rs.next()){    row = sheet.createRow(index++);    //聲明列    for(int i=0;i<cols;i++){     String val = rs.getString(i+1);     //聲明列     HSSFCell cel = row.createCell(i);     //放資料     cel.setCellValue(val);    }   }  }  con.close();  book.write(new FileOutputStream("d:/a/"+dbName+".xls")); }

以上就是本文的全部內容,希望對大家的學習有所協助。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.