Java將Excel表格中資料匯入至資料庫中的表中
阿新 • • 發佈:2018-11-11
上一節介紹了Java將資料庫表中資料匯出至Excel表格,那麼本節來介紹它的逆過程,也就是將Excel表格中的資料逐行匯入資料庫中的表中,依然需要使用Apache的POI,上一節已經說過也附了這個jar包的下載地址,這一節就不過多的說,直接講如何將Excel表格中的資料逐行匯入資料庫中的表中,還是放程式碼。
public static void main(String[] args) { HSSFWorkbook book; try { book = new HSSFWorkbook(new FileInputStream("E:/axls/blogs.xls")); HSSFSheet sheet=book.getSheet("表"); //得到表格的第一行 HSSFRow row=sheet.getRow(0); Iterator<Cell> ite=row.cellIterator(); while(ite.hasNext()){ HSSFCell cell=(HSSFCell)ite.next(); String cname=cell.getStringCellValue(); System.out.print(cname); System.out.print(","); } System.out.println("\n"); System.out.println("---------------------------------------"); //得到表格的其他行,即不包括第一行 Iterator<Row> it= sheet.rowIterator(); while(it.hasNext()){//遍歷所有行 row=(HSSFRow)it.next(); ite=row.cellIterator(); while(ite.hasNext()){//遍歷當前行的所有列 HSSFCell cell=(HSSFCell)ite.next(); String cname=cell.getStringCellValue(); System.out.print(cname); System.out.print(","); } System.out.println("\n"); } book.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
通過以上程式碼就可以將表格中的資料逐行讀取出來了,如下圖是控制檯的輸出。如果想把每一行逐行新增到資料庫中表中,只需在程式中加入資料庫插入語言即可(當然前提是你的程式中已經匯入了連線資料庫的jar包,本地或伺服器已經安裝了資料庫)。