Java將資料庫資料匯入EXCEL

來源:互聯網
上載者:User

Java將資料庫資料匯入EXCEL

一般的資料庫資料怎麼匯入excel中呢??這讓人很疑惑,今天我找到了一個方法可以實現

需要匯入一個第三方包

具體內容如下:

裡面含有指導文檔,index.html裡面含有如何讀取資料庫檔案到excel和excel資料到資料庫中。

主要用到一個包

將這個包拷貝到項目裡面就可以了。

先做一個簡單版本的helloword

 

[html] view plaincopyprint? 
  1.      span>public void mkexcel() throws Exception{  
  2.         //首先在記憶體中建立好工作薄  
  3.         HSSFWorkbook book =new HSSFWorkbook();//建立好工作薄  
  4.         HSSFSheet sheet = book.createSheet("表一");//表單名以及表單  
  5.         HSSFRow row=sheet.createRow(4);//建立行數     
  6.         HSSFCell cell=row.createCell(4);//建立列數  
  7.         cell.setCellValue("大哥哥,加油!!");//將資料寫到cell中去  
  8.         //記憶體中建立可不行,必須要寫到檔案  
  9.         FileOutputStream out =new FileOutputStream("a.xls");  
  10.         book.write(out);  
  11.     }  
  12.       
  13.  
:

 

通過上面的簡單一實例,我們能發現,建立xls的檔案類似於在網頁中動態建立table表格類似點擊開啟連結

1,建立工作薄

2,薄建立表

3,表建行

4,行建列

5,列裡面設值

有了上面的這個簡單的介紹,現在開始匯入資料庫裡面的內容

1,我們必須從記憶體中建立工作薄

 

[html] view plaincopyprint? 
  1.    span>HSSFWorkbook book =new HSSFWorkbook(); span>  

 

 

2,建立sheet的時候,我們需要指定sheet名,所有需要用到中繼資料得到database裡面的table名

 

[html] view plaincopyprint? 
  1. span>  span>Connection con =hibernateFactory2.getCon();//資料庫連接成功 span>  

 DatabaseMetaData dmeta=con.getMetaData();//中繼資料

 

[html] view plaincopyprint? 
  1.    span>ResultSet rs=dmeta.getCatalogs();//獲得所有的資料庫,但是為了方便,我們直接指定資料庫名 span>  
  2. span>  

 

 

3,獲得table名,

 

[html] view plaincopyprint? 
  1.        span>String dName="hncu";  
  2.         //獲得資料庫裡面的表名,返回ResultSet 全部放在list中  
  3.         ResultSet rs=   dmeta.getTables(dName, dName, null, new String[]{"TABLE"});  
  4.         //放在list 中,為後面的sheet名  
  5.         List list =new ArrayList();  
  6.         while(rs.next())  
  7.         {  
  8.           

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.