當前位置:才華齋>IT認證>JAVA認證>

Java將excel資料匯入資料庫的方法

JAVA認證 閱讀(1.54W)

很多時候拼接字串是很多專案必須做的,該程式碼中我們拼接了不少sql語句,也許有更簡單的方式,可以使用java將excel裡的資料匯入到資料庫裡,下面一起來看看使用java將excel裡的`資料匯入到資料庫裡的基本方法,僅供參考。

Java將excel資料匯入資料庫的方法

  /**將execl資料匯入資料庫

* @author trsli

* */

public class CreateDBTable {

private static Connection conn;

private static String sql="";

private static StringBuffer buf=new StringBuffer();

static{

conn=onnection();

}

public static void main(String[] args) {

  //資料。xls檔案路徑

tln("輸入檔案路徑:");

String filename=new Scanner()。nextLine();

  //獲取需要插入資料庫的資料內容

Object[][] contents=new PoiUtil()。getmessage(filename);

  //獲取資料庫建立表格的欄位名

Object[] titles=new PoiUtil()。gettitles(filename);

tln("輸入數表格名:");

String fname=new Scanner()。nextLine();

try {

String ziduan="";

String blank="";

PreparedStatement stmt=areStatement(sql);

nd("create table "+fname+"( id int primary key auto_increment");

  //拼接字串,主要是為了完全實現動態建立資料表格以及後期插入資料

for(int i=0;i

nd(","+titles[i]+" varchar(20)");

if(i==th-1){//字串末尾沒有","

ziduan+=titles[i]+"";

blank+="?";

}else{

ziduan+=titles[i]+",";

blank+="?,";

}

}

   //sql資料拼裝完成

sql="insert into "+fname+"("+ziduan+") values ("+ blank+")";

nd(" );");

uteUpdate(ring());

tln("預處理…");