本文實(shí)例為大家分享了java將某個(gè)數(shù)據(jù)庫(kù)的表全部導(dǎo)出到excel中的方法,供大家參考,具體內(nèi)容如下
第一步:如何用POI操作Excel
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
@Test public void createXls() throws Exception{ //聲明一個(gè)工作薄 HSSFWorkbook wb = new HSSFWorkbook(); //聲明表 HSSFSheet sheet = wb.createSheet( "第一個(gè)表" ); //聲明行 HSSFRow row = sheet.createRow( 7 ); //聲明列 HSSFCell cel = row.createCell( 3 ); //寫(xiě)入數(shù)據(jù) cel.setCellValue( "你也好" ); FileOutputStream fileOut = new FileOutputStream( "d:/a/b.xls" ); wb.write(fileOut); fileOut.close(); } |
第二步:導(dǎo)出指定數(shù)據(jù)庫(kù)的所有表
分析:
1:某個(gè)數(shù)數(shù)據(jù)庫(kù)有多少表,表名是什么?―――DataBaseMetadate.getMetadate().getTables(null,null,null,new String[]{Table}); - excel的文件名稱(chēng)。
2:對(duì)每一個(gè)表進(jìn)行select * 操作。 - 每一個(gè)sheet的名稱(chēng)。
3:分析表結(jié)構(gòu),rs.getMetadate(); ResultSetMedated
4:多個(gè)列,列名是什么. - 字段名就是sheet的第一行信息。
5:獲取每一行的數(shù)據(jù) – 放到sheet第一行以后。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
|
@Test public void export() throws Exception{ //聲明需要導(dǎo)出的數(shù)據(jù)庫(kù) String dbName = "focus" ; //聲明book HSSFWorkbook book = new HSSFWorkbook(); //獲取Connection,獲取db的元數(shù)據(jù) Connection con = DataSourceUtils.getConn(); //聲明statemen Statement st = con.createStatement(); //st.execute("use "+dbName); DatabaseMetaData dmd = con.getMetaData(); //獲取數(shù)據(jù)庫(kù)有多少表 ResultSet rs = dmd.getTables(dbName,dbName, null , new String[]{ "TABLE" }); //獲取所有表名 - 就是一個(gè)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; //查詢數(shù)據(jù) rs = st.executeQuery(sql); //根據(jù)查詢的結(jié)果,分析結(jié)果集的元數(shù)據(jù) ResultSetMetaData rsmd = rs.getMetaData(); //獲取這個(gè)查詢有多少行 int cols = rsmd.getColumnCount(); //獲取所有列名 //創(chuàng)建第一行 HSSFRow row = sheet.createRow( 0 ); for ( int i= 0 ;i<cols;i++){ String colName = rsmd.getColumnName(i+ 1 ); //創(chuàng)建一個(gè)新的列 HSSFCell cell = row.createCell(i); //寫(xiě)入列名 cell.setCellValue(colName); } //遍歷數(shù)據(jù) 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); //放數(shù)據(jù) cel.setCellValue(val); } } } con.close(); book.write( new FileOutputStream( "d:/a/" +dbName+ ".xls" )); } |
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助。