当前位置: 移动技术网 > IT编程>开发语言>Java > JSP上传excel及excel插入至数据库的方法

JSP上传excel及excel插入至数据库的方法

2017年12月12日  | 移动技术网IT编程  | 我要评论

引蛇出洞服务,活塞舞,火车票 刷票

本文实例讲述了jsp上传excel及excel插入至数据库的方法。分享给大家供大家参考。具体如下:

此导入excel是与pojo绑定的,(缺点)excle表头必须是pojo的字段值

1. html页面:

<form id="myform" method="post" enctype="multipart/form-data">
<table>
 <tr>
  <td></td>
  <td>
   <input type="file" name="filepath" id="filepath"
    class="easyui-validatebox" required=true
    validtype="equallength[4]" missingmessage="文件!" value="" />
  </td>
 </tr>
 <tr align="center">
  <td colspan="2">
   <a id="btn1" class="easyui-linkbutton"
    data-options="iconcls:'icon-ok'" style="width: 60px"
    onclick="subform();">ok</a>
   <a id="btn2" class="easyui-linkbutton"
    data-options="iconcls:'icon-cancel'" style="width: 60px"
    onclick="closedig();">cancel</a>
  </td>
 </tr>
</table>
</form>
<script type="text/javascript">
function subform(){
 if($('#myform').form('validate')){
  /**
  var filepath = $("#filepath").val();
  alert(filepath);
  $.ajax({
   url: 'excleimport',
   typs: "post",
   data: {"filepath":filepath},
   async: false,
    error: function(request) {
    $('#dg').datagrid('reload');
    closedig();
    $.messager.alert("操作提示", "操作成功!","info");
    },
    success: function(data) {
     alert("success");
    }
  });
  **/
  var filepath = $("#filepath").val();
  var re = /(\\+)/g; 
  var filename = filepath.replace(re,"#"); 
  //对路径字符串进行剪切截取 
  var one = filename.split("#"); 
  //获取数组中最后一个,即文件名 
  var two = one[one.length-1]; 
  //再对文件名进行截取,以取得后缀名 
  var three = two.split("."); 
   //获取截取的最后一个字符串,即为后缀名 
  var last = three[three.length-1]; 
  //添加需要判断的后缀名类型 
  var tp = "xls,xlsx"; 
  //返回符合条件的后缀名在字符串中的位置 
  var rs = tp.indexof(last); 
  if(rs != -1){ 
   $("#myform").attr("action","excleimport");
   $("#myform").submit();
  }else{ 
   $.messager.alert("操作提示", "您选择的上传文件不是有效xls或者xlsx文件!","error");
   return false; 
  } 
 } else {
  $.messager.alert("操作提示", "请选择上传文件!","error");
 }
}
</script>

2. java代码:

@requestmapping("/excleimport")
 public void excleimport(httpservletrequest request) throws ioexception, exception {
  request.setcharacterencoding("utf-8"); //设置编码 
  //获得磁盘文件条目工厂 
  diskfileitemfactory factory = new diskfileitemfactory(); 
  //获取文件需要上传到的路径 
  string path = request.getrealpath("/upload/kaku"); 
  file uploaddir = new file(path);
  if (!uploaddir.exists()) {
   uploaddir.mkdirs();
  }
  factory.setrepository(uploaddir); 
  //设置 缓存的大小,当上传文件的容量超过该缓存时,直接放到 暂时存储室 
  factory.setsizethreshold(1024*1024) ; 
  //高水平的api文件上传处理 
  servletfileupload upload = new servletfileupload(factory); 
  //可以上传多个文件 
  list<fileitem> list = (list<fileitem>)upload.parserequest(request); 
  for(fileitem item : list) 
  { 
   //获取表单的属性名字 
   string name = item.getfieldname(); 
   //如果获取的 表单信息是普通的 文本 信息 
   if(item.isformfield()) 
   {      
    //获取用户具体输入的字符串 ,名字起得挺好,因为表单提交过来的是 字符串类型的 
    string value = item.getstring() ; 
    request.setattribute(name, value); 
   } 
   //对传入的非 简单的字符串进行处理 ,比如说二进制的 图片,电影这些 
   else 
   { 
    /** 
     * 以下三步,主要获取 上传文件的名字 
     */ 
    //获取路径名 
    string value = item.getname() ; 
    //索引到最后一个反斜杠 
    int start = value.lastindexof("\\"); 
    //截取 上传文件的 字符串名字,加1是 去掉反斜杠, 
    string filename = value.substring(start+1); 
    //文件后缀名
    string prefix = filename.substring(filename.lastindexof(".") + 1);
    cardcenter cardcenter = new cardcenter();
    request.setattribute(name, filename); 
    //真正写到磁盘上 
    //它抛出的异常 用exception 捕捉 
    //item.write( new file(path,filename) );//第三方提供的 
    //手动写的 
    //outputstream out = new fileoutputstream(new file(path,filename)); 
    inputstream in = item.getinputstream() ; 
    list<cardcenter> listfromexcel = (list<cardcenter>)exelutil.exportlistfromexcel(in, prefix, cardcenter);
    this.cardcenterservice.excleimport(listfromexcel);
    /*int length = 0 ; 
    byte [] buf = new byte[1024] ; 
    system.out.println("获取上传文件的总共的容量:"+item.getsize()); 
    // in.read(buf) 每次读到的数据存放在 buf 数组中 
    while( (length = in.read(buf) ) != -1) 
    { 
     //在 buf 数组中 取出数据 写到 (输出流)磁盘上 
     out.write(buf, 0, length); 
    } */
    in.close(); 
    //out.close(); 
   } 
  } 
}

3. java代码:

public class exelutil { 
 //第一列开始
 private static int start = 0;
 //最后一列序号
 private static int end =0;
 public static string getsubstring(string str){
  return str.substring(0,str.lastindexof("."));
 }
 /** 
  * 方法描述:由excel文件的sheet导出至list
  * @param file
  * @param sheetnum
  * @return
  * @throws ioexception
  * @author 
  * @date 2013-3-25 下午10:44:26
  * @comment
  */
 public static list<?> exportlistfromexcel(file file, string fileformat,object dtoobj) 
   throws ioexception { 
  return exportlistfromexcel(new fileinputstream(file), fileformat,dtoobj); 
 } 
 /** 
  * 方法描述:由excel流的sheet导出至list 
  * @param is
  * @param extensionname
  * @param sheetnum
  * @return
  * @throws ioexception
  * @author 
  * @date 2013-3-25 下午10:44:03
  * @comment
  */
 public static list<?> exportlistfromexcel(inputstream is,string fileformat,object dtoobj) throws ioexception { 
  workbook workbook = null; 
  if (fileformat.equals(bizconstant.xls)) { 
   workbook = new hssfworkbook(is); 
  } else if (fileformat.equals(bizconstant.xlsx)) { 
   workbook = new xssfworkbook(is); 
  } 
  return exportlistfromexcel(workbook,dtoobj); 
 } 
 /**
  * 方法描述:由指定的sheet导出至list
  * @param workbook
  * @param sheetnum
  * @return
  * @author 
  * @date 2013-3-25 下午10:43:46
  * @comment
  */
 private static list<object> exportlistfromexcel(workbook workbook ,object dtoobj) {
  list<object> list = new arraylist<object>();
  string[] model = null;
  sheet sheet = workbook.getsheetat(0); 
  // 解析公式结果 
  formulaevaluator evaluator = workbook.getcreationhelper().createformulaevaluator(); 
  int minrowix = sheet.getfirstrownum(); 
  int maxrowix = sheet.getlastrownum(); 
  for (int rowix = minrowix; rowix <= maxrowix; rowix++) { 
   object obj = null;
   if(rowix==minrowix){
    start = sheet.getrow(rowix).getfirstcellnum();
    end = sheet.getrow(rowix).getlastcellnum();
   }
   row row = sheet.getrow(rowix); 
   stringbuilder sb = new stringbuilder();  
   for (int i = start; i < end; i++) { 
    cell cell = row.getcell(new integer(i)); 
    cellvalue cellvalue = evaluator.evaluate(cell); 
    if (cellvalue == null) { 
     sb.append(bizconstant.separator+null);
     continue; 
    } 
    // 经过公式解析,最后只存在boolean、numeric和string三种数据类型,此外就是error了 
    // 其余数据类型,根据官方文档,完全可以忽略 
    switch (cellvalue.getcelltype()) { 
    case cell.cell_type_boolean: 
     sb.append(bizconstant.separator + cellvalue.getbooleanvalue()); 
     break; 
    case cell.cell_type_numeric: 
     // 这里的日期类型会被转换为数字类型,需要判别后区分处理 
     if (dateutil.iscelldateformatted(cell)) { 
      sb.append(bizconstant.separator + cell.getdatecellvalue()); 
     } else { 
      sb.append(bizconstant.separator + cellvalue.getnumbervalue()); 
     } 
     break; 
    case cell.cell_type_string: 
     sb.append(bizconstant.separator + cellvalue.getstringvalue()); 
     break; 
    case cell.cell_type_formula: 
     break; 
    case cell.cell_type_blank: 
     break; 
    case cell.cell_type_error: 
     break; 
    default: 
     break; 
    } 
   } 
   if(rowix==minrowix){
    string index = string.valueof(sb);
    string realmodel =index.substring(1, index.length());
    model =realmodel.split(",");
   }else{
    string index = string.valueof(sb);
    string realvalue =index.substring(1, index.length());
    string[] value =realvalue.split(",");
    //字段映射
    try {
     dtoobj =dtoobj.getclass().newinstance();
    } catch (instantiationexception e) {
     e.printstacktrace();
    } catch (illegalaccessexception e) {
     e.printstacktrace();
    }
    obj = reflectutil(dtoobj,model,value);
    list.add(obj);
   }
  } 
  return list; 
 } 
 /**
  * 方法描述:字段映射赋值
  * @param objone
  * @param listname
  * @param listvales
  * @return
  * @author 
  * @date 2013-3-25 下午10:53:43
  * @comment
  */
 @suppresswarnings("deprecation")
 private static object reflectutil(object objone, string[] listname,
   string[] listvales) {
  field[] fields = objone.getclass().getdeclaredfields();
  for (int i = 0; i < fields.length; i++) {
   fields[i].setaccessible(true);
   for (int j = 0; j < listname.length; j++) {
    if (listname[j].equals(fields[i].getname())) {
     try {
      if (fields[i].gettype().getname().equals(java.lang.string.class.getname())) { 
       // string type
       if(listvales[j]!=null){
        fields[i].set(objone, listvales[j]);
       }else{
        fields[i].set(objone, "");
       }
      } else if (fields[i].gettype().getname().equals(java.lang.integer.class.getname())
        || fields[i].gettype().getname().equals("int")) { 
       // integer type 
       if(listvales[j]!=null){
        fields[i].set(objone, (int)double.parsedouble(listvales[j])); 
       }else{
        fields[i].set(objone, -1); 
       }
      }else if(fields[i].gettype().getname().equals("date")){
       //date type
       if(listvales[j]!=null){
        fields[i].set(objone, date.parse(listvales[j]));
       } 
      }else if(fields[i].gettype().getname().equals("double")
        ||fields[i].gettype().getname().equals("float")){
       //double
       if(listvales[j]!=null){
        fields[i].set(objone, double.parsedouble(listvales[j])); 
       }else{
        fields[i].set(objone, 0.0); 
       }
      }
     } catch (illegalargumentexception e) {
      e.printstacktrace();
     } catch (illegalaccessexception e) {
      e.printstacktrace();
     }
     break;
    }
   }
  }
  return objone;
 }
}

希望本文所述对大家的jsp程序设计有所帮助。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网