当前位置: 移动技术网 > IT编程>开发语言>Java > SpringMVC上传和解析Excel方法

SpringMVC上传和解析Excel方法

2019年07月22日  | 移动技术网IT编程  | 我要评论

示例:导入相关数据(excel文件),相关的文件数据编辑好。

xml文件配置

再spring的xml文件中配置要上传文件的大小

<!-- 上传文件拦截,设置最大上传文件大小 10m=10*1024*1024(b)=10485760 bytes --> 
<bean id="multipartresolver" class="org.springframework.web.multipart.commons.commonsmultipartresolver"> 
 <property name="maxuploadsize" value="10485760" /> 
</bean>

jsp界面配置

<div>
  <form id="sourcefile" name="sourcefile" action="" method="post" enctype="multipart/form-data">
  <input type="button" value="添 加" onclick="addairline()" />
  <input style="margin-left: 20px;" id="source_file" name="sourcefile" type="file" value="选择文件" />
  <input style="margin-left: 20px;" data-loading-text="请勿重复提交" type="submit" value="上 传" onclick="uppolicy()">
  <input style="margin-left: 20px;" type="submit" value="下载模板" onclick="return downloadtemplate();">
  </form>
 </div>

js文件

function uppolicy() {
  document.sourcefile.action = "/login/policy/uploadcsv";
  var submiturl = document.getelementbyid("sourcefile").attributes["action"].value;
  $.ajax({
  type: "post",
  url: submiturl,
  data: $('#sourcefile').serialize(),
  datatype: "json",
  success: function (result) {
   var json = json.parse(result);
   if (json.flag == "0" || json.flag == "1") {
   alert(tablejson.success);
   return;
   }
  }
  })
 }
 

controller配置

@requestmapping(value = "/uploadcsv" ,method = requestmethod.post)
 @responsebody
 public string uploadcsv(@requestparam("sourcefile") multipartfile sourcefile, httpservletrequest request,httpservletresponse response) throws ioexception{

  //判断文件是否为空
  if (sourcefile==null) return null;
  //获取文件名
  string name=sourcefile.getoriginalfilename();
  //进一步判断文件是否为空(即判断其大小是否为0或其名称是否为null)
  long size =sourcefile.getsize();
  if (name==null ||("").equals(name) && size==0) return null;

  //批量导入。参数:文件名,文件。
  boolean b = batchimport(name,sourcefile);
  jsonobject jsonobject=new jsonobject();
  if(b){
   jsonobject.put("flag",0);
   jsonobject.put("success","批量导入excel成功!");
  }else{
   jsonobject.put("flag",1);
   jsonobject.put("success","批量导入excel失败!");
  }
  return jsonobject.tostring();
 }

分层没有那么的详细,再controller中做的处理

public boolean batchimport(string name,multipartfile file){
  boolean b = false;
  //创建处理excel
  excelutils readexcel=new excelutils();
  //解析excel,获取客户信息集合。
  list<otapolicymodel> cpolicylist = readexcel.getexcelinfo(name ,file);

  if(cpolicylist != null){
   b = true;
  }

  //迭代添加信息(注:实际上这里也可以直接将cpolicylist集合作为参数,
    在mybatis的相应映射文件中使用foreach标签进行批量添加。)
  for(otapolicymodel customer:cpolicylist){
   policydao.insertotapolicy(customer);
  }
  return b;
 }

工具类excelutils.java

    即上述方法中readexcel.getexcelinfo(name ,file);语句所调用的方法以及其他相关的方法
apache poi提供api给java程式对microsoft office格式档案读和写的功能。不过这首先得判断excel的版本而选择不同的workbook的方式(2003版本对应的是hssfworkbook,2007版本及以上对应的是xssfworkbook)。此外,一般来说先将在客户端用户上传的文件拷贝一份至服务器的本地磁盘中,然后再从这个拷贝文件中进行读取,这样就避免了因客户端的网络异常或其他状况而在读取时造成的数据流失或损坏的情况。

package com.flight.inter.otaadapter.commons.util;

import com.flight.inter.otaadapter.model.otapolicymodel;
import org.apache.poi.hssf.usermodel.hssfworkbook;
import org.apache.poi.ss.usermodel.cell;
import org.apache.poi.ss.usermodel.row;
import org.apache.poi.ss.usermodel.sheet;
import org.apache.poi.ss.usermodel.workbook;
import org.apache.poi.xssf.usermodel.xssfworkbook;
import org.springframework.web.multipart.multipartfile;
import org.springframework.web.multipart.commons.commonsmultipartfile;

import java.io.*;
import java.math.bigdecimal;
import java.util.arraylist;
import java.util.date;
import java.util.list;

/**
 * created by ling.zhang on 2016/12/29.
 */
public class excelutils {

 //总行数
 private int totalrows = 0;
 //总条数
 private int totalcells = 0;
 //错误信息接收器
 private string errormsg;
 //构造方法
 public excelutils(){}
 //获取总行数
 public int gettotalrows() { return totalrows;}
 //获取总列数
 public int gettotalcells() { return totalcells;}
 //获取错误信息
 public string geterrorinfo() { return errormsg; }

 /**
  * 验证excel文件
  * @param filepath
  * @return
  */
 public boolean validateexcel(string filepath){
  if (filepath == null || !(wdwutil.isexcel2003(filepath) || wdwutil.isexcel2007(filepath))){
   errormsg = "文件名不是excel格式";
   return false;
  }
  return true;
 }

 /**
  * 读excel文件,获取客户信息集合
  * @param
  * @return
  */
 public list<otapolicymodel> getexcelinfo(string filename, multipartfile mfile){

  //把spring文件上传的multipartfile转换成commonsmultipartfile类型
  commonsmultipartfile cf= (commonsmultipartfile)mfile; //获取本地存储路径
  file file = new file("d:\\fileupload");
  //创建一个目录 (它的路径名由当前 file 对象指定,包括任一必须的父路径。)
  if (!file.exists()) file.mkdirs();
  //新建一个文件
  file file1 = new file("d:\\fileupload" + new date().gettime() + ".xlsx");
  //将上传的文件写入新建的文件中
  try {
   cf.getfileitem().write(file1);
  } catch (exception e) {
   e.printstacktrace();
  }

  //初始化客户信息的集合
  list<otapolicymodel> customerlist=new arraylist<otapolicymodel>();
  //初始化输入流
  inputstream is = null;
  try{
   //验证文件名是否合格
   if(!validateexcel(filename)){
    return null;
   }
   //根据文件名判断文件是2003版本还是2007版本
   boolean isexcel2003 = true;
   if(wdwutil.isexcel2007(filename)){
    isexcel2003 = false;
   }
   //根据新建的文件实例化输入流
   is = new fileinputstream(file1);
   //根据excel里面的内容读取客户信息
   customerlist = getexcelinfo(is, isexcel2003);
   is.close();
  }catch(exception e){
   e.printstacktrace();
  } finally{
   if(is !=null)
   {
    try{
     is.close();
    }catch(ioexception e){
     is = null;
     e.printstacktrace();
    }
   }
  }
  return customerlist;
 }
 /**
  * 根据excel里面的内容读取客户信息
  * @param is 输入流
  * @param isexcel2003 excel是2003还是2007版本
  * @return
  * @throws ioexception
  */
 public list<otapolicymodel> getexcelinfo(inputstream is,boolean isexcel2003){
  list<otapolicymodel> customerlist=null;
  try{
   /** 根据版本选择创建workbook的方式 */
   workbook wb = null;
   //当excel是2003时
   if(isexcel2003){
    wb = new hssfworkbook(is);
   }
   else{//当excel是2007时
    wb = new xssfworkbook(is);
   }
   //读取excel里面客户的信息
   customerlist=readexcelvalue(wb);
  }
  catch (ioexception e) {
   e.printstacktrace();
  }
  return customerlist;
 }
 /**
  * 读取excel里面客户的信息
  * @param wb
  * @return
  */
 private list<otapolicymodel> readexcelvalue(workbook wb){
  //得到第一个shell
  sheet sheet=wb.getsheetat(0);

  //得到excel的行数
  this.totalrows=sheet.getphysicalnumberofrows();

  //得到excel的列数(前提是有行数)
  if(totalrows>=1 && sheet.getrow(0) != null){
   this.totalcells=sheet.getrow(0).getphysicalnumberofcells();
  }

  list<otapolicymodel> otapolicymodellist=new arraylist<otapolicymodel>();
  otapolicymodel otapolicymodel;
  //循环excel行数,从第二行开始。标题不入库
  for(int r=1;r<totalrows;r++){
   row row = sheet.getrow(r);
   if (row == null) continue;
   otapolicymodel = new otapolicymodel();
   try {
    thread.currentthread().sleep(1);
   }catch (interruptedexception e){
    e.printstacktrace();
   }
   otapolicymodel.setpolicyid(system.currenttimemillis());
   //循环excel的列
   for(int c = 0; c <this.totalcells; c++){
    cell cell = row.getcell(c);
    if (null != cell){
     if(c==0){
      otapolicymodel.setsource(cell.getstringcellvalue());//供应商
     }else if(c==1){
      otapolicymodel.setvendee(cell.getstringcellvalue());//输出渠道
     }else if(c==2){
      int triptype=0;
      if (cell.getstringcellvalue()=="全部"){
       triptype=0;
      }else if (cell.getstringcellvalue().equals("单程")){
       triptype=10;
      }else if (cell.getstringcellvalue().equals("往返")){
       triptype=20;
      }else if (cell.getstringcellvalue().equals("单程直飞")){
       triptype=11;
      }else if (cell.getstringcellvalue().equals("单程中转")){
       triptype=12;
      }else if (cell.getstringcellvalue().equals("往返直飞")){
       triptype=21;
      }else if (cell.getstringcellvalue().equals("往返中转")){
       triptype=22;
      }
      otapolicymodel.settriptype(triptype);//行程类型
     }else if(c==3){
      otapolicymodel.setcarrier(cell.getstringcellvalue());//航司代码
     }else if(c==4){
      otapolicymodel.setdepcity(cell.getstringcellvalue());//起飞城市
     }else if(c==5){
      otapolicymodel.setarrcity(cell.getstringcellvalue());//降落城市
     }else if(c==6){
      otapolicymodel.setsalebegindatel(new bigdecimal(cell.getnumericcellvalue()).setscale(0,bigdecimal.round_half_down).longvalue());//销售开始日期
     }else if(c==7){
      otapolicymodel.setsaleenddatel(new bigdecimal(cell.getnumericcellvalue()).setscale(0,bigdecimal.round_half_down).longvalue());//销售结束日期
     }else if(c==8){
      otapolicymodel.settravelbegindatel(new bigdecimal(cell.getnumericcellvalue()).setscale(0,bigdecimal.round_half_down).longvalue());//旅行开始日期
     }else if(c==9){
      otapolicymodel.settravelenddatel(new bigdecimal(cell.getnumericcellvalue()).setscale(0,bigdecimal.round_half_down).longvalue());//旅行结束日期
     }else if(c==10){
      int cabintype=9;
      if (cell.getstringcellvalue().equals("全部")){
       cabintype=9;
      }else if (cell.getstringcellvalue().equals("经济舱")){
       cabintype=1;
      }else if (cell.getstringcellvalue().equals("商务")){
       cabintype=2;
      }else if (cell.getstringcellvalue().equals("头等")){
       cabintype=3;
      }
      otapolicymodel.setcabintype(cabintype);//舱位等级
     }else if(c==11){

      otapolicymodel.setfdtype(cell.getstringcellvalue().equals("按价格区间")?1:2);//返点类型
     }else if(c==12){
      otapolicymodel.setcabin(cell.getstringcellvalue());//舱位
     }else if(c==13){
      otapolicymodel.setpricebegin(cell.getnumericcellvalue());//最低价格
     }else if(c==14){
      otapolicymodel.setpriceend(cell.getnumericcellvalue());//最高价格
     }else if(c==15){
      otapolicymodel.setlmoney(cell.getnumericcellvalue());//留钱
     }else if(c==16){
      otapolicymodel.setfpercent(cell.getnumericcellvalue());//全价返点
     }else if(c==17){
      otapolicymodel.setftpercent(cell.getnumericcellvalue());//票面返点
     }else if(c==18){
      int carrierlimit=2;
      if (cell.getstringcellvalue().equals("是")){
       carrierlimit=1;
      }else if (cell.getstringcellvalue().equals("否")){
       carrierlimit=0;
      }else if (cell.getstringcellvalue().equals("无")){
       carrierlimit=2;
      }
      otapolicymodel.setcarrierlimit(carrierlimit);//开票航司限制
     }else if(c==19){
      int transport=2;
      if (cell.getstringcellvalue().equals("是")){
       transport=1;
      }else if (cell.getstringcellvalue().equals("否")){
       transport=0;
      }else if (cell.getstringcellvalue().equals("无限制")){
       transport=2;
      }
      otapolicymodel.settransport(transport);//支持联运
     }else if(c==20){
      int sharedflight=2;
      if (cell.getstringcellvalue().equals("是")){
       sharedflight=1;
      }else if (cell.getstringcellvalue().equals("否")){
       sharedflight=0;
      }else if (cell.getstringcellvalue().equals("无")){
       sharedflight=2;
      }
      otapolicymodel.setsharedflight(sharedflight);//支持共享航班
     }else if(c==21){
      otapolicymodel.setpstatus(cell.getstringcellvalue().equals("有效")?1:2);//状态
     }else if(c==22){
      int faretype=0;
      if (cell.getstringcellvalue().equals("私有")){
       faretype=1;
      }else if (cell.getstringcellvalue().equals("公布")){
       faretype=2;
      }else if (cell.getstringcellvalue().equals("全部")){
       faretype=0;
      }
      otapolicymodel.setfaretype(faretype);//运价类型
     }else if(c==23){
      otapolicymodel.setlimitprice(new bigdecimal(cell.getnumericcellvalue()).setscale(0,bigdecimal.round_half_down).longvalue());//加价限制
     }else if(c==24){
      int limittransit=2;
      if (cell.getstringcellvalue().equals("全部")){
       limittransit=2;
      }else if (cell.getstringcellvalue().equals("适用")){
       limittransit=0;
      }else if (cell.getstringcellvalue().equals("不适用")){
       limittransit=1;
      }
      otapolicymodel.setlimittransit(limittransit);//中转限制
     }else if(c==25){
      otapolicymodel.setarrcity(cell.getstringcellvalue());//中转城市
     }else if(c==26){
      int limitnation=2;
      if (cell.getstringcellvalue().equals("全部")){
       limitnation=2;
      }else if (cell.getstringcellvalue().equals("适用")){
       limitnation=0;
      }else if (cell.getstringcellvalue().equals("不适用")){
       limitnation=1;
      }
      otapolicymodel.setlimitnation(limitnation);//国籍限制
     }else if(c==27){
      otapolicymodel.setarrcity(cell.getstringcellvalue());//国籍
     }else if (c==28){
      otapolicymodel.setusername(cell.getstringcellvalue());//用户名
     }

    }
   }
   //添加客户
   otapolicymodellist.add(otapolicymodel);
  }
  return otapolicymodellist;
 }

}

工具类wdwutil.java

package com.flight.inter.otaadapter.commons.util;

/** 
* created by ling.zhang on 2016/12/29. 
*/ 
public class wdwutil { 
// @描述:是否是2003的excel,返回true是2003 
public static boolean isexcel2003(string filepath) { 
return filepath.matches(“^.+\.(?i)(xls)$”); 
}

//@描述:是否是2007的excel,返回true是2007
public static boolean isexcel2007(string filepath) {
 return filepath.matches("^.+\\.(?i)(xlsx)$");
}
}

    说明:上面的代码为了阅读便利而先贴的是父方法,后贴的是子方法,而在实际的代码编辑中一般是先编辑子方法,后编辑父方法,如上面应该是先编辑工具类的代码,再编辑服务层的代码,最后编辑控制器的代码。

    这样,整个流程就可以了,赶紧拿去测试吧

更多精彩内容,请点击 《spring上传下载专题》进行深入学习和研究。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网