您的位置:首页 > 编程语言 > Java开发

用Java JXL实现从excel读出数据转入数据库及例子

2013-06-14 09:52 417 查看
今天给别人做东西,结果对方提出了这个要求:能不能把excel里的数据直接导入数据库?

回来在网上一查,还真有一个这样的java包。叫jxl。也是sourceForge上的一个项目。大家可以搜一下,这里提供下载地址(工程名叫jexcelapi)。http://www.jspcn.net/htmldown/11248971876251883.html

下载来之后就可以用这提供的类来excel文件了。

先建一个excel文件abc.xls.放到E盘根目录下。形如下:

namesecondName
hot1leave1
hot2leave2
然后在数据库里建表。

CREATE TABLE `name` (

`name` varchar(30) default NULL,

`secondname` varchar(20) default NULL

) ENGINE=InnoDB DEFAULT CHARSET=utf8

/*

* Excel2Mysql.java

*

* Created on 2006年9月25日, 下午6:48

*

* To change this template, choose Tools | Template Manager

* and open the template in the editor.

*/

package excel;

/**

*

* @author hotleave

*/

import java.io.*;

import jxl.*;

import java.sql.*;

public class Excel2Mysql {

public static Connection conn=null;

public static Statement stmt=null;

/** Creates a new instance of Excel2Mysql */

public Excel2Mysql() {

try{

Class.forName("org.gjt.mm.mysql.Driver").newInstance();

conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test?user=root&password=123456&characterEncoding=UTF-8");

}catch(Exception e){

System.out.println(e.getMessage());

}

}

public static void main(String args[]){

try{

Class.forName("org.gjt.mm.mysql.Driver").newInstance();

conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test?user=user&password=pwd&characterEncoding=UTF-8");

stmt=conn.createStatement();

}catch(Exception e){

System.out.println(e.getMessage());

}

try{

InputStream is = new FileInputStream("e:/abc.xls");

Workbook book=Workbook.getWorkbook(is);//获得一个工作表对象

Sheet sheet=book.getSheet(0);//取得第一个工作表,也可用sheet名字获得。

int len=sheet.getRows();//取得行数

String sql="";

System.out.println("len is:"+len);

Cell[] cells=null;

System.out.println("读出来的结果为:");

for(int i=1;i<len;i++){//从1开始,避免插入标题

//System.out.println(i);

cells=null;

cells=sheet.getRow(i);

sql="insert into name values ('"+cells[0].getContents()+"','" +

cells[1].getContents()+"')";

stmt.execute(sql);

System.out.println("ok");

//System.out.println("cells len is:"+cells.length);

for(int j=0;j<cells.length;j++){//打印每行信息

System.out.print(cells[j].getContents()+" ");

}

System.out.println("");

}

book.close();

}catch(Exception e){

System.out.println(e);

}

}

}

呵呵,大家自己试一下吧。可以创造出来更多的东西啊。结合一下smartUpoad也许能做一个在线处理的。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: