EXCEL中與資料庫打交道的好工具-JXL

來源:互聯網
上載者:User
   經常要將EXCEL和資料庫打交道的話,建議推薦使用一個好的開源工具JXL,下面小結如何將其EXCEL資料匯入到資料庫,
以及如何把資料庫的資料匯出到EXCEL.

1) EXCEL的表格匯入資料庫
   假設有一個EXCEL,有兩個SHEET,記得第一個sheet序號是0,第2個sheet的序號是1.
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;

主要方法為:

   InputStream fs = null;
   Workbook rbw = null;
    try{

       try {      
           fs=new FileInputStream(file);   
           rbw=Workbook.getWorkbook(fs);
           System.out.println("載入本地excel檔案成功!");   
           } catch (FileNotFoundException e){
             e.printStackTrace();
           } catch (BiffException e){
             e.printStackTrace();
           } catch (IOException e){
             e.printStackTrace();
           }
       
    
      Sheet book=null;
      Sheet bookSingle=null;
      try{
      book=rbw.getSheet(0);//第一個sheet
         }catch (Exception e){
      e.printStackTrace();   
      }
         System.out.println("取得excel檔案sheet成功!"); 

         rsRows=book.getRows();//擷取第一個sheet表的總行數
            for(int i=1;i<rsRows;i++){   
           //擷取excel檔案中資料  
           //第i行第0列
          Cell cell0 = book.getCell(0, i);
          String usercode=cell0.getContents();
                   
          //第i行第1列
          Cell cell1 = book.getCell(1, i);
          String org_name=cell1.getContents();
         }
   注意這裡的book.getCell(0,i),是從第I行第0列這樣寫的,就是反過來

2) 資料庫到EXCEL
    File file=new File("xxx.xls");
 WritableWorkbook book = Workbook.createWorkbook(new File(fileName));

    // 產生名為“SheetOne”的工作表,參數0表示這是第一個sheet
    WritableSheet sheet = book.createSheet("SheetOne", 0);

   // 在Label對象的構造子中指名儲存格位置是第一列第一行(0,0),以及儲存格內容
        Label chs_name_LbTitle=new Label(0, 0, "中文名稱");

     ............................................
         sheet.addCell(chs_name_LbTitle);

 Label ent_name_cCell=new Label(0, 1, 要寫入的實際資料);
sheet.addCell(ent_name_cCell);
 book.write();
    book.close();

聯繫我們

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