經常要將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();