在实际应用中,经常会遇到上传excel或者下载excel的情况,比如导入数据、下载统计数据等等场景。针对这个问题,我写了个基于springmvc的简单上传下载示例,其中excel的处理使用apache的poi组件。
主要依赖的包如下:
<dependency> <groupid>commons-io</groupid> <artifactid>commons-io</artifactid> <version>2.4</version> </dependency> <dependency> <groupid>commons-fileupload</groupid> <artifactid>commons-fileupload</artifactid> <version>1.3.1</version> </dependency> <dependency> <groupid>org.springframework</groupid> <artifactid>spring-web</artifactid> <version>4.0.0.release</version> </dependency> <dependency> <groupid>org.springframework</groupid> <artifactid>spring-webmvc</artifactid> <version>4.0.0.release</version> </dependency> <dependency> <groupid>org.apache.poi</groupid> <artifactid>poi</artifactid> <version>3.10.1</version> </dependency>
相关处理类:
(一)controller类
package com.research.spring.controller; import java.io.ioexception; import java.util.arraylist; import java.util.hashmap; import java.util.list; import java.util.map; import org.apache.poi.hssf.usermodel.hssfworkbook; import org.apache.poi.ss.usermodel.row; import org.apache.poi.ss.usermodel.sheet; import org.apache.poi.ss.usermodel.workbook; import org.springframework.stereotype.controller; import org.springframework.web.bind.annotation.requestmapping; import org.springframework.web.bind.annotation.requestparam; import org.springframework.web.multipart.multipartfile; import org.springframework.web.servlet.modelandview; import com.research.spring.model.userinfo; import com.research.spring.view.excelview; @controller @requestmapping("/file") public class filecontroller { /** * excel文件上传处理 * @param file * @return */ @requestmapping("/upload") public modelandview uploadexcel(@requestparam("file") multipartfile file){ list<userinfo> list = new arraylist<userinfo>(); //这里只处理文件名包括“用户”的文件,模板使用下载模板 if( file.getoriginalfilename().contains("用户") ){ try { workbook wb = new hssfworkbook(file.getinputstream()); sheet sheet = wb.getsheetat(0); for( int i = 1; i <= sheet.getlastrownum(); i++ ){ row row = sheet.getrow(i); userinfo info = new userinfo(); info.setusername(row.getcell(0).getstringcellvalue()); info.setpassword(row.getcell(1).getstringcellvalue()); list.add(info); } } catch (ioexception e) { e.printstacktrace(); } } modelandview mav = new modelandview("content"); mav.addobject("content",list.tostring()); return mav; } /** * excel文件下载处理 */ @requestmapping("/download") public modelandview downloanexcel(){ list<userinfo> list = new arraylist<userinfo>(); userinfo userinfo = new userinfo(); userinfo.setpassword("0000"); userinfo.setusername("sdfas"); list.add(userinfo); list.add(userinfo); list.add(userinfo); list.add(userinfo); map<string,list<userinfo>> map = new hashmap<string, list<userinfo>>(); map.put("infolist", list); excelview ve = new excelview(); return new modelandview(ve,map); } }
(二)实体类
package com.research.spring.model; public class userinfo { private string username; private string password; public string getusername() { return username; } public void setusername(string username) { this.username = username; } public string getpassword() { return password; } public void setpassword(string password) { this.password = password; } @override public string tostring() { return "userinfo [username=" + username + ", password=" + password + "]"; } }
(三)view类
这个类在下载时用到,在spring渲染页面时使用自定义的view类进行excel的相关处理。
package com.research.spring.view; import java.io.outputstream; import java.net.urlencoder; import java.util.list; import java.util.map; import javax.servlet.http.httpservletrequest; import javax.servlet.http.httpservletresponse; 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.springframework.web.servlet.view.document.abstractexcelview; import com.research.spring.model.userinfo; /** * 下载excel视图 * * @author wdmcygah * */ public class excelview extends abstractexcelview { @override protected void buildexceldocument(map<string, object> model, hssfworkbook workbook, httpservletrequest request, httpservletresponse response) throws exception { @suppresswarnings("unchecked") list<userinfo> list = (list<userinfo>) model.get("infolist"); if (list != null && list.size() != 0) { int len = list.size(); sheet sheet = workbook.createsheet(); // 第一行文字说明 row row = sheet.createrow(0); cell cell = row.createcell(0, cell.cell_type_string); cell.setcellvalue("用户名"); cell = row.createcell(1, cell.cell_type_string); cell.setcellvalue("密码"); //下面是具体内容 for (int i = 0; i < len; i++) { row = sheet.createrow(i + 1); cell = row.createcell(0, cell.cell_type_string); cell.setcellvalue(list.get(i).getusername()); cell = row.createcell(1, cell.cell_type_string); cell.setcellvalue(list.get(i).getpassword()); } } response.setcontenttype("application/vnd.ms-excel"); response.setcharacterencoding("utf-8"); //这里对文件名进行编码,保证下载时汉字显示正常 string filename = urlencoder.encode("用户.xls", "utf-8"); //content-disposition属性设置成以附件方式进行下载 response.setheader("content-disposition", "attachment;filename=" + filename); outputstream os = response.getoutputstream(); workbook.write(os); os.flush(); os.close(); } }
(四)主要配置文件
上传文件时需要在配置文件中配置multipartresolver类,配置后spring会自动将文件传成multipartfile对象,然后就可以进行相应的处理。示例看controller类。
<?xml version="1.0" encoding="utf-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:util="http://www.springframework.org/schema/util" xsi:schemalocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd"> <context:component-scan base-package="com.research" /> <bean class="org.springframework.web.servlet.view.internalresourceviewresolver"> <property name="viewclass" value="org.springframework.web.servlet.view.jstlview" /> <property name="prefix" value="/web-inf/" /> <property name="suffix" value=".jsp" /> </bean> <!-- 上传文件解析器配置 --> <bean id="multipartresolver" class="org.springframework.web.multipart.commons.commonsmultipartresolver"> <property name="defaultencoding" value="utf-8"></property> <!-- 上传文件的大小限制 ,单位是字节--> <property name="maxuploadsize" value="5242880000000"></property> <!-- 上传文件的临时路径,上传完成后会自动删除 --> <property name="uploadtempdir" value="upload/temp"></property> </bean> </beans>
(五)测试页面
<html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> </head> <body> <h3>测试下载excel功能</h3> <form action="file/download.htm" enctype="multipart/form-data" method="post"> <input type="submit" value="下载excel"></input> </form> <h3>测试上传excel功能</h3> <form action="file/upload.htm" enctype="multipart/form-data" method="post"> <input type="file" name="file"></input> <input type="submit" value="上传excel"></input> </form> </body> </html>
如果想看完整源码,可以到我的github仓库查看。 其中,上传文件只处理符合下载模板的文件。若要处理其它文件需要自实现。代码测试通过无误。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。
如对本文有疑问, 点击进行留言回复!!
springmvc之ResponseBody响应json数据遇到的错误及解决
uni-app 后台升级 静默升级 uniapp 后台更新 静默更新 在线升级
SpringBoot多Module启动报错Could not transfer metadata
Hibernate项目报错:Cannot call sendError() after the response has been committed
网友评论