java实现Excel导入数据库
2009-09-17 00:00:00 来源:WEB开发网Struts.xml代码
<action name="excel" class="com.skyarm.action.FeaturesAction" method="uplode">
<result>/success.jsp</result>
</action>
Featuresaction.java代码
public class FeaturesAction extends ActionSupport {
private static final long serialVersionUID = -34341L;
// private static final int BUFFER_SIZE = 16 * 1024;
private File theFile;
private String roleid;
public String uplode(){
int i = UplodeService.uplode(roleid,theFile);
return SUCCESS;
}
public String getRoleid() {
return roleid;
}
public void setRoleid(String roleid) {
this.roleid = roleid;
}
public File getTheFile() {
return theFile;
}
public void setTheFile(File theFile) {
this.theFile = theFile;
}
}
Uplodeservice.java代码
public class UplodeService {
public static void uplode(String id,File file){
int rows = 0; //表单行数
Sheet sh = null; //表单对象
InputStream inputStream = null;
Workbook book = null;
Connection conn = null;
PreparedStatement stmt = null;
try {
inputStream = new FileInputStream(file);
book = Workbook.getWorkbook(inputStream);
sh = book.getSheet(0);
rows = sh.getRows();
conn = DataModule.getConnection();
String sql = "INSERT INTO auth_user_role (userid,roleid) VALUES (?,?)";
String userid;
for(int i=0;i<rows;i++){ // 程序只取第一列
userid = sh.getCell(0, i).getContents();
//判断userid的合法性
// if(5>userid.length() || 8<userid.length())
// return 0;
stmt = conn.prepareStatement(sql);
stmt.setString(1, userid);
stmt.setString(2, id);
stmt.executeUpdate();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (BiffException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}finally{
if(inputStream!=null)
try {
inputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(book!=null)
book.close();
DataModule.close(stmt);
DataModule.close(conn);
}
}
}
更多精彩
赞助商链接