本文執行個體為大家分享了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")); }
以上就是本文的全部內容,希望對大家的學習有所協助。