經常要將EXCEL和數(shù)據(jù)庫打交道的話,建議推薦使用一個好的開源工具JXL,下面小結如何將其EXCEL數(shù)據(jù)導入到數(shù)據(jù)庫,
以及如何把數(shù)據(jù)庫的數(shù)據(jù)導出到EXCEL.
1) EXCEL的表格導入數(shù)據(jù)庫
假設有一個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表的總行數(shù)
for(int i=1;i<rsRows;i++){
//獲取excel文件中數(shù)據(jù)
//第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) 數(shù)據(jù)庫到EXCEL
File file=new File("xxx.xls");
WritableWorkbook book = Workbook.createWorkbook(new File(fileName));
// 生成名為“SheetOne”的工作表,參數(shù)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, 要寫入的實際數(shù)據(jù));
sheet.addCell(ent_name_cCell);
book.write();
book.close();
標簽:java培訓課程 java軟件工程師培訓 java就業(yè)培訓教程 java培訓機構 java培訓班 java軟件培訓