服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Java教程 - Java对Excel表格的上传和下载处理方法

Java对Excel表格的上传和下载处理方法

2020-12-11 14:50blue_wz Java教程

这篇文章主要介绍了Java对Excel表格的上传和下载处理方法,需要的朋友可以参考下

excel表格文件的上传下载,java中涉及到文件肯定会有io流的知识。

而excel文件就要涉及到poi技术,而excel的版本包括:2003-2007和2010两个版本, 即excel的后缀名为:xls和xlsx。

这里我是按照正规的项目流程做的案例,所以可能会比网上的一些demo复杂一些。不过文件的上传和下载基本都是一套固定的流程,只是每个人的实现方式不太相同。

数据库我用的是mysql。

下面是我的项目目录:

Java对Excel表格的上传和下载处理方法

按照正常的项目做了分层处理,文件上传的业务我放到了service处理,而文件下载业务还在controller层。

对前端请求处理,我分成了两个方法都放在handleexcelcontroller里面,这个类继承了baseexcelcontroller,基本的文件操作处理在baseexcelcontroller里面。

baseexcelcontroller继承了basecontroller,basecontroller类是所有controller的父类,这里用到的不太多,这个类封装了response返回值等的处理等一些方法。

项目中除了springmvc和mybatis的jar包之外还引入了:

Java对Excel表格的上传和下载处理方法

上传和下载excel文件:

1、创建需要上传的excel文件,为了简化,我这里只写了四列,即四个字段

Java对Excel表格的上传和下载处理方法

2、创建jsp页面

  1. <%@ page language="java" import="java.util.*" pageencoding="utf-8"%> 
  2. <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> 
  3. <!doctype html public "-//w3c//dtd html 4.01 transitional//en"
  4. <html> 
  5.  <head> 
  6.  <title>excel文件处理</title> 
  7.  <script type="text/javascript" src="<c:url value='/res/js/jquery.js'/>"></script> 
  8.  <script> 
  9.   $(function(){ 
  10.    var $wrap = $(".wrap"); 
  11.    var find = function(str){ 
  12.     return $wrap.find(str); 
  13.    } 
  14.    var getjname = function(name){ 
  15.     return find("input[name='"+name+"']"); 
  16.    } 
  17.    getjname("upload").click(function(){ 
  18.      var form = new formdata(document.getelementbyid("tf")); 
  19.      $.ajax({ 
  20.      url:"<c:url value='/file/uploadexcel'/>"
  21.      type:"post"
  22.      data:form, 
  23.      datatype:"json"
  24.      processdata:false
  25.      contenttype:false
  26.      success:function(data){ 
  27.       //window.clearinterval(timer);     
  28.        if(data.success == "success"){ 
  29.         alert("提交文件成功,已将数据存入数据库"); 
  30.        } 
  31.      }, 
  32.      error:function(e){ 
  33.       alert("错误!"); 
  34.       //window.clearinterval(timer); 
  35.      } 
  36.     }); 
  37.     }) 
  38.    getjname("download").click(function(){ 
  39.     $.post("<c:url value='/file/downloadexcel'/>",{"id":"3"},function(data){ 
  40.      //alert("下载文件成功"); 
  41.     },"json"
  42.    }) 
  43.   }) 
  44.  </script> 
  45.  </head> 
  46.  <body> 
  47.   <div class="wrap"
  48.    <form id="tf"
  49.     <p> 
  50.      <input type="file" name="file" value="选择文件"/> 
  51.     excel文件上传:<input type="button" name="upload" value="upload"/> 
  52.    </p> 
  53.    <p> 
  54.     excel文件下载:<input type="button" name="download" value="updown"/> 
  55.    </p>    
  56.    </form> 
  57.   </div> 
  58.  </body> 
  59. </html> 

3、依次创建controller、service、domain、mapper层,注意它们的依赖关系

1)、controller层的处理,在handleexcelcontroller里面注入baseexcelservice。因为只是做个示范,所欲我这里将泛型固定为students类

 baseexcelcontroller代码:

  1. package cn.wangze.controller; 
  2. import java.io.file; 
  3. import java.io.fileinputstream; 
  4. import java.io.filenotfoundexception; 
  5. import java.io.fileoutputstream; 
  6. import java.io.ioexception; 
  7. import java.io.inputstream; 
  8. import java.lang.reflect.method; 
  9. import java.text.simpledateformat; 
  10. import java.util.collection; 
  11. import java.util.date; 
  12. import java.util.iterator; 
  13. import java.util.list; 
  14. import javax.servlet.http.httpservletresponse; 
  15. import org.apache.commons.lang.stringutils; 
  16. import org.apache.poi.hssf.usermodel.hssfcell; 
  17. import org.apache.poi.hssf.usermodel.hssfcellstyle; 
  18. import org.apache.poi.hssf.usermodel.hssffont; 
  19. import org.apache.poi.hssf.usermodel.hssfpalette; 
  20. import org.apache.poi.hssf.usermodel.hssfrichtextstring; 
  21. import org.apache.poi.hssf.usermodel.hssfrow; 
  22. import org.apache.poi.hssf.usermodel.hssfsheet; 
  23. import org.apache.poi.hssf.usermodel.hssfworkbook; 
  24. import org.apache.poi.hssf.util.cellrangeaddress; 
  25. import org.apache.poi.hssf.util.hssfcolor; 
  26. import org.apache.poi.ss.usermodel.sheet; 
  27. import org.apache.poi.xssf.usermodel.xssfworkbook; 
  28. import org.springframework.web.multipart.multipartfile; 
  29. import cn.wangze.domain.students; 
  30. public class baseexcelcontroller extends basecontroller{ 
  31.  //获取文件的路径 
  32.  string separator = system.getproperty("file.separator"); 
  33.  //验证元素是否为空 
  34.  @suppresswarnings("all"
  35.  public boolean isempty(object obj){ 
  36.   if(obj instanceof object[]){ 
  37.    if(((object[]) obj).length==0){ 
  38.     return true
  39.    } 
  40.    if(obj == nullreturn true
  41.    if((string.valueof(obj).trim()).length() == 0){ 
  42.     return true
  43.    } 
  44.    if(obj instanceof list){ 
  45.     if(((list) obj) == null || ((list)obj).size() == 0){ 
  46.      return true
  47.     } 
  48.    } 
  49.   } 
  50.   return false
  51.  } 
  52.  /** 
  53.   * 文件上传部分 
  54.   * */ 
  55.  //验证文件 
  56.  protected boolean checkpathname(string filename,httpservletresponse response){ 
  57.   //验证文件是否存在 
  58.   if(isempty(filename)){ 
  59.    senderror("上传文件不存在",response); 
  60.    return false
  61.   } 
  62.   //验证文件是否是以xls或者xlsx做后缀的文件,如果不是就返回错误信息 
  63.   if(!(stringutils.endswithignorecase(filename,".xls")||stringutils.endswithignorecase(filename, ".xlsx"))){ 
  64.    senderror("上传文件类型错误,请核对后重新上传?",response); 
  65.   } 
  66.   return true
  67.  } 
  68.  //获取文件的sheet 
  69.  protected sheet getsheet(multipartfile file,string path,string filename) throws illegalstateexception, ioexception{ 
  70.   //找到要存放到项目里面的路径,新建文件 
  71.   file targetfile = new file(path, filename); 
  72.   targetfile.mkdirs(); 
  73.   if (targetfile.exists()) { 
  74.    targetfile.delete(); 
  75.    file.transferto(targetfile); 
  76.   } else { 
  77.    file.transferto(targetfile); 
  78.   } 
  79.   //封装输入流,封装sheet里面的内容 
  80.   inputstream is = null
  81.   try
  82.    is = new fileinputstream(path+separator+filename); 
  83.    //判断版本是否为excel加强版 
  84.    if(stringutils.endswithignorecase(filename, ".xls")){ 
  85.     return new hssfworkbook(is).getsheetat(0); 
  86.    }else if(stringutils.endswithignorecase(filename, ".xlsx")){ 
  87.     return new xssfworkbook(is).getsheetat(0); 
  88.    } 
  89.    return null
  90.   } 
  91.   finally
  92.    if(is != null){ 
  93.     is.close(); 
  94.    } 
  95.   } 
  96.  } 
  97.  /** 
  98.   * 文件下载部分 
  99.   * */ 
  100.  //根据传入的sting值,判断生成在excel表的位置 
  101.  private hssfcellstyle getpublicstyle(hssfworkbook workbook,string key){ 
  102.   hssffont font = workbook.createfont(); 
  103.   hssfcellstyle style = workbook.createcellstyle(); 
  104.   hssfpalette custompalette = workbook.getcustompalette(); 
  105.   custompalette.setcoloratindex(hssfcolor.teal.index, (byte) 64, (byte) 148, (byte) 160); 
  106.   custompalette.setcoloratindex(hssfcolor.orange.index, (byte) 170, (byte) 204, (byte) 204); 
  107.   style.setalignment(hssfcellstyle.align_center); 
  108.   style.setverticalalignment(hssfcellstyle.vertical_center); 
  109.   if(key=="head"){ 
  110.     style.setfillpattern(hssfcellstyle.solid_foreground); 
  111.     font.setfontheightinpoints((short)12); 
  112.     font.setcolor(hssfcolor.teal.index); 
  113.     font.setboldweight(hssffont.boldweight_bold); 
  114.     style.setfont(font); 
  115.   } 
  116.   if(key=="title"){ 
  117.     font.setcolor(hssfcolor.white.index); 
  118.     font.setboldweight(hssffont.boldweight_bold); 
  119.     style.setborderleft(hssfcellstyle.border_thin); 
  120.     style.setleftbordercolor(hssfcolor.white.index); 
  121.     style.setborderright(hssfcellstyle.border_thin); 
  122.     style.setrightbordercolor(hssfcolor.white.index); 
  123.     style.setfont(font); 
  124.     style.setfillpattern(hssfcellstyle.solid_foreground); 
  125.     style.setfillforegroundcolor(hssfcolor.orange.index); 
  126.     style.setfillbackgroundcolor(hssfcolor.orange.index); 
  127.   } 
  128.   return style; 
  129.  } 
  130.  //创建head头信息 
  131.  private void createhead(hssfsheet sheet,hssfcellstyle style,string[] title){ 
  132.   hssfrow row1 = sheet.createrow(0); 
  133.   hssfcell celltitle = row1.createcell(0); 
  134.   celltitle.setcellvalue(new hssfrichtextstring(title[0])); 
  135.   sheet.addmergedregion(new cellrangeaddress(0,0,0,title.length-2)); 
  136.   celltitle.setcellstyle(style); 
  137.  } 
  138.  //创建title信息 
  139.  private void createtitle(hssfsheet sheet,hssfcellstyle style,string[] label,int columnnum){ 
  140.   hssfrow row2 = sheet.createrow(1);    
  141.   hssfcell cell1 = null;    
  142.   for(int n=0;n<columnnum;n++){ 
  143.    cell1 = row2.createcell(n);    
  144.    cell1.setcellvalue(label[n+1]);      
  145.    cell1.setcellstyle(style);    
  146.   } 
  147.  } 
  148.  //创建content数据信息 
  149.  private void createcontent(hssfsheet sheet,hssfcellstyle style,collection<students> list,int columnnum,string[] parameters){ 
  150.   int index= 0; 
  151.   iterator<students> it = list.iterator(); 
  152.   while(it.hasnext()){ 
  153.    index++; 
  154.     students cash = it.next(); 
  155.     int num2 = parameters.length; 
  156.     hssfrow row = sheet.createrow(index+1);  
  157.     initcells(style, num2,cash, parameters,row); 
  158.   } 
  159.  } 
  160.  //验证是否为中文 
  161.  public boolean checkchinese(string s){ 
  162.   int n=0; 
  163.   boolean flag =false
  164.   for(int i=0; i<s.length(); i++) { 
  165.     n = (int)s.charat(i); 
  166.     flag=(19968 <= n && n <40623)?true:false
  167.   } 
  168.   return flag; 
  169.  } 
  170.  //将数据设置到excel表格内 
  171.  public void initcells(hssfcellstyle style, int columnnum, students t, 
  172.   string[] endcontent, hssfrow row3) { 
  173.   for(int j=0;j<columnnum;j++){ 
  174.     hssfcell cell = row3.createcell(j); 
  175.     string fieldname = endcontent[j]; 
  176.     try
  177.      if(fieldname!="" && !checkchinese(fieldname)){ 
  178.       string getmethodname = "get" +fieldname.substring(0,1).touppercase()+fieldname.substring(1); 
  179.       class clazz = t.getclass(); 
  180.       method getmethod = clazz.getmethod(getmethodname, new class[]{}); 
  181.       string value = (string)getmethod.invoke(t, new object[]{}); 
  182.       cell.setcellvalue(value);         
  183.      }else
  184.       cell.setcellvalue(fieldname); 
  185.      } 
  186.      cell.setcellstyle(style); 
  187.     }catch(exception e){ 
  188.      e.printstacktrace(); 
  189.     } 
  190.    } 
  191.  } 
  192.  public void createend(hssfsheet sheet,hssfcellstyle style,int numtext,int columnnum,students t,string[] endcontent){ 
  193.   hssfrow row3 = sheet.createrow(numtext+2); 
  194.   initcells(style, columnnum, t, endcontent, row3); 
  195.  } 
  196.  //根据service查询到的数据,创建excel表并插入查询的数据信息 
  197.  protected string getoutputname(list<students> list, string path, string[] title, string[] parameters, students t, string[] endcontent) 
  198.   throws ioexception{ 
  199.   //根据传入的title数组的第一个值,设置文件名称 
  200.   string filename = title[0]+"_"new simpledateformat("yyyymmdd").format(new date())+".xls"
  201.   //输出流放到文件的本地位置 
  202.   fileoutputstream fos = new fileoutputstream(path+separator+filename); 
  203.   //列数,根据title的个数,除去第一个就是每列title的信息 
  204.   int columnnum = title.length-1; 
  205.   int numtext = list.size(); 
  206.   hssfworkbook workbook = new hssfworkbook();  
  207.   hssfsheet sheet = workbook.createsheet();      
  208.   sheet.setdefaultcolumnwidth (20);      
  209.   sheet.setdefaultrowheight((short)400); 
  210.   hssfcellstyle contentstyle = this.getpublicstyle(workbook,"");     
  211.   hssfcellstyle titlestyle = this.getpublicstyle(workbook,"title");     
  212.   hssfcellstyle headerstyle = this.getpublicstyle(workbook,"head");     
  213.   createhead(sheet,headerstyle,title); 
  214.   createtitle(sheet,titlestyle,title,columnnum); 
  215.   createcontent(sheet,contentstyle,list,columnnum,parameters); 
  216.   //createend(sheet,contentstyle,numtext,columnnum,t,endcontent); 
  217.   workbook.write(fos); 
  218.   fos.flush();   
  219.   fos.close();  
  220.   return filename; 
  221.  } 

handleexcelcontroller用来处理前端请求,代码如下:

  1. package cn.wangze.controller; 
  2. import java.io.file; 
  3. import java.util.list; 
  4. import javax.servlet.servletoutputstream; 
  5. import javax.servlet.http.httpservletresponse; 
  6. import javax.servlet.http.httpsession; 
  7. import org.apache.commons.io.fileutils; 
  8. import org.springframework.beans.factory.annotation.autowired; 
  9. import org.springframework.stereotype.controller; 
  10. import org.springframework.web.bind.annotation.requestmapping; 
  11. import org.springframework.web.multipart.multipartfile; 
  12. import cn.wangze.domain.students; 
  13. import cn.wangze.service.baseexcelservice; 
  14. @controller 
  15. @requestmapping("/file"
  16. public class handleexcelcontroller extends baseexcelcontroller{ 
  17.  @autowired 
  18.  private baseexcelservice baseexcelservice; 
  19.  @requestmapping("/uploadexcel"
  20.  public void uploadexcel(multipartfile file,httpsession session,httpservletresponse response) throws exception{ 
  21.   //如果上传的文件不存在,抛出异常 
  22.   if(file == null){ 
  23.    throw new exception("文件不存在"); 
  24.   } 
  25.   //获取文件名 
  26.   string filename = file.getoriginalfilename(); 
  27.   //选择上传的文件存放到项目的路径 
  28.   string path = session.getservletcontext().getrealpath(separator+"res"+separator+"upload"); 
  29.   if(!checkpathname(filename,response)) return ; 
  30.   string msg = baseexcelservice.loadexcel(getsheet(file, path, filename)); 
  31.   sendmsg(true,msg,response);  
  32.  } 
  33.  @requestmapping("/downloadexcel"
  34.  public void updownexcel(students student,httpservletresponse res,httpsession session,httpservletresponse response) 
  35.   throws exception{ 
  36.   list<students> stus = baseexcelservice.querylist(student); 
  37.   if(stus.size()==0){ 
  38.    res.sendredirect("/index.jsp"); 
  39.    return
  40.   } 
  41.   //下载的excel文件存放的本地路径 
  42.   string path = session.getservletcontext().getrealpath(separator+"res"+separator+"exportexcel"+separator); 
  43.   servletoutputstream os = res.getoutputstream(); 
  44.   students t = baseexcelservice.querytotal(student); 
  45.   //标题文字,数值中的第一个值+当前日期为文件名称,以后的每个元素为每列的标题 
  46.   string[] title={"studets04","id","名字","年龄","性别"};//标题文字 
  47.   //对应实体类的属性值 
  48.   string[] parameters ={"id","name","age","sex"}; 
  49.   string[] endcontent = {"","","",""}; 
  50.   //调用父类的处理方法,生成excel文件 
  51.   string filename = getoutputname(stus,path,title,parameters,t,endcontent); 
  52.   try { 
  53.     res.reset(); 
  54.    res.setcharacterencoding("utf8"); 
  55.    res.setcontenttype("application/vnd.ms-excel;charset=utf8"); 
  56.    res.setheader("content-disposition""attachment;filename=" 
  57.       +new string(filename.getbytes("utf-8"),"iso-8859-1")); 
  58.    os.write(fileutils.readfiletobytearray(new file(path+separator+filename))); 
  59.    sendresult(true,response); 
  60.    os.flush(); 
  61.   } finally { 
  62.    if (os != null) { 
  63.     os.close(); 
  64.    } 
  65.   } 
  66.  } 

2)、service层的处理,把studentsmapper注入到baseexcelservice

baseexcelservice代码:

  1. package cn.wangze.service; 
  2. import java.util.arraylist; 
  3. import java.util.hashmap; 
  4. import java.util.list; 
  5. import java.util.map; 
  6. import javax.servlet.servletoutputstream; 
  7. import javax.servlet.http.httpsession; 
  8. import org.apache.poi.ss.usermodel.cell; 
  9. import org.apache.poi.ss.usermodel.row; 
  10. import org.apache.poi.ss.usermodel.sheet; 
  11. import org.springframework.beans.factory.annotation.autowired; 
  12. import org.springframework.stereotype.service; 
  13. import cn.wangze.domain.students; 
  14. import cn.wangze.mapper.studentsmapper; 
  15. @service 
  16. public class baseexcelservice { 
  17.  @autowired 
  18.  private studentsmapper<students> studentsmapper; 
  19.  //判断字符串是否为空 
  20.  public boolean isempty(string str) { 
  21.   return str == null || str.length() == 0; 
  22.  } 
  23.  //获取单个表格(字段)存放的信息 
  24.  private string getvalue(cell cell,string celllable,map<string,string> errmap){ 
  25.   cell.setcelltype(cell.cell_type_string); 
  26.   string value = cell.getstringcellvalue().trim(); 
  27.   return value; 
  28.  } 
  29.  //通过这个方法将excel表的每行的数据放到info对象里面 
  30.  private string addinfo(row row,students info){ 
  31.   map<string,string> errmap = new hashmap<string,string>(); 
  32.   string id = getvalue(row.getcell(0),"id",errmap); 
  33.   string username = getvalue(row.getcell(1),"姓名",errmap); 
  34.   string age = getvalue(row.getcell(2),"年龄",errmap); 
  35.   string sex = getvalue(row.getcell(3),"性别",errmap); 
  36.   string errmsg = errmap.get("errmsg"); 
  37.   if(!isempty(errmsg)){ 
  38.    return errmsg; 
  39.   } 
  40.   info.setid(id); 
  41.   info.setname(username); 
  42.   info.setage(age); 
  43.   info.setsex(sex); 
  44.   return null
  45.  } 
  46.  public string loadexcel(sheet sheet) throws exception{ 
  47.   //新建一个list集合,用来存放所有行信息,即每行为单条实体信息 
  48.   list<students> infos = new arraylist<students>(); 
  49.   //获取到数据行数,第一行是title,不需要存入数据库,所以rownum从1开始 
  50.   for (int rownum = 1; rownum <= sheet.getlastrownum(); rownum++) { 
  51.    students info = new students(); 
  52.    string errmsg2 = addinfo(sheet.getrow(rownum),info); 
  53.    if(errmsg2 != nullreturn errmsg2; 
  54.    infos.add(info); 
  55.   } 
  56.   if(infos.isempty()){ 
  57.    return "没有解析到学生数据,请查验excel文件"
  58.   } 
  59.   //通过studentsmapper的insertsheetdata方法,将实体类存放的数据插入到数据库 
  60.   int result = studentsmapper.insertsheetdata(infos); 
  61.   //若插入成功会返回大于1的整数,返回success 
  62.   if(result >= 1){ 
  63.    return "success"
  64.   } 
  65.   return "error"
  66.  } 
  67.  //查询所有数据库存放的学生信息 
  68.  public list<students> querylist(students students){ 
  69.   return studentsmapper.querylist(students); 
  70.  } 
  71.  //获取到的学生实体信息 
  72.  public students querytotal(students students){ 
  73.   return studentsmapper.querytotal(students); 
  74.  } 
  75.  public void downexcel(httpsession session,string separator){ 
  76.  } 

3)、实体层的处理,字段要对应excel表的字段

  1. package cn.wangze.domain; 
  2. public class students { 
  3.  string id; 
  4.  string name; 
  5.  string age; 
  6.  string sex; 
  7.  public string getid() { 
  8.   return id; 
  9.  } 
  10.  public void setid(string id) { 
  11.   this.id = id; 
  12.  } 
  13.  public string getname() { 
  14.   return name; 
  15.  } 
  16.  public void setname(string name) { 
  17.   this.name = name; 
  18.  } 
  19.  public string getage() { 
  20.   return age; 
  21.  } 
  22.  public void setage(string age) { 
  23.   this.age = age; 
  24.  } 
  25.  public string getsex() { 
  26.   return sex; 
  27.  } 
  28.  public void setsex(string sex) { 
  29.   this.sex = sex; 
  30.  } 

4)、dao层处理:studentsmapper.java是一个接口,业务到数据库需要执行的方法在这里声明,studentsmapper.xml相当于接口的实现类,用来连接java和数据库的操作。

studentsmapper.java代码:

  1. package cn.wangze.mapper; 
  2. import java.util.list; 
  3. public interface studentsmapper<t> { 
  4.  public int insertsheetdata(list<t> list); 
  5.  public list<t> querylist(t t); 
  6.  public t querytotal(t t); 

studentsmapper.xml代码:

  1. <?xml version="1.0" encoding="utf-8"?> 
  2. <!doctype mapper public "-//mybatis.org//dtd mapper 3.0//en" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"
  3. <mapper namespace="cn.wangze.mapper.studentsmapper"
  4.  <sql id="columnlist"
  5.   id,name,age,sex 
  6.  </sql> 
  7.  <sql id="columnlist_t" > 
  8.   t.id,t.name,t.age,t.sex 
  9.  </sql> 
  10.  <sql id="valuelist"
  11.   #{id},#{name},#{age},#{sex} 
  12.  </sql> 
  13.  <sql id="whereclause"
  14.   where 1=1 
  15.   <if test="id!=null and id!=''">and id=#{id}</if
  16.   <if test="name!=null and name!=''">and name=#{name}</if
  17.   <if test="age!=null and age!=''">and age=#{age}</if
  18.   <if test="sex!=null and sex!=''">and sex=#{sex}</if
  19.  </sql> 
  20.  <sql id="whereclause_pager" > 
  21.   where 1=1 
  22.   <if test="t.id!=null and t.id!=''">and id=#{t.id}</if
  23.   <if test="t.name!=null and t.name!=''">and name=#{t.name}</if
  24.   <if test="t.age!=null">and age=#{t.age}</if
  25.   <if test="t.sex!=null and t.sex!=''">and sex=#{t.sex}</if
  26.  </sql> 
  27.  <sql id="setclause" > 
  28.   set 
  29.   <trim suffixoverrides="," > 
  30.    <if test="id!=null">id=#{id},</if
  31.    <if test="name!=null">name=#{name},</if
  32.    <if test="pid!=null">age=#{age},</if
  33.    <if test="url!=null">sex=#{sex},</if
  34.   </trim> 
  35.  </sql> 
  36.  <select id="querylist" resulttype="students"
  37.   select <include refid="columnlist"/> from students 
  38.  </select> 
  39.  <select id="querytotal" parametertype="students" resulttype="students"
  40.   select <include refid="columnlist" /> from students <include refid="whereclause"/> 
  41.   <!-- (select <include refid="columnlist"/> from t_account_cash t 
  42.     <include refid="whereclausequery"/> group by to_char(t.add_time,'yyyy-mm-dd'),t.account_id) a --> 
  43.  </select> 
  44.  <insert id="insertsheetdata" usegeneratedkeys="true" parametertype="java.util.list"
  45.   <!-- <selectkey resulttype="long" keyproperty="id" order="after"
  46.    select 
  47.    last_insert_id() 
  48.   </selectkey> --> 
  49.   insert into students (id,name,age,sex) 
  50.   values 
  51.   <foreach collection="list" item="item" index="index" separator="," > 
  52.    (#{item.id},#{item.name},#{item.age},#{item.sex}) 
  53.   </foreach> 
  54.  </insert> 
  55. </mapper> 

所有的代码就是这些了,操作的时候需要注意的多是路径的问题。最复杂的就是baseexcelcontroller的操作,它做的事情就是解析上传和创建下载excel文件。

执行完之后的结果图是这样:

在数据库查看上传的excel表:

Java对Excel表格的上传和下载处理方法

下载到d: omcat omcat6.0.32webappsexcelhandledemo esexportexcel文件夹下的excel表:

Java对Excel表格的上传和下载处理方法

这里有一点不足的地方,我相信你已经发现了,就是下载完excel表格之后,前端还没有和业务对接上,没有相应的提示来告诉操作人执行结果,只能通过代码设置好的路径去查看文件夹下是否有下载的excel文件,

不过这都是细节问题,相信难不倒聪明的各位。

总结

以上所述是小编给大家介绍的java对excel表格的上传和下载处理方法,希望对大家有所帮助

原文链接:http://www.cnblogs.com/blue-wz/archive/2017/08/05/7290493.html

延伸 · 阅读

精彩推荐