실제 애플리케이션에서는 데이터 가져 오기, 통계 다운로드 등과 같이 Excel이 업로드 또는 다운로드되는 상황에 종종 발생합니다.이 문제를 해결하기 위해 Excel의 처리가 Apache의 POI 구성 요소를 사용하는 SpringMVC를 기반으로 간단한 업로드 다운로드 예제를 작성했습니다.
주요 종속성은 다음과 같습니다.
<pectionency> <groupId> Commons-Io </groupId> <artifactid> Commons-Io </artifactid> <bersion> 2.4 </version> </dependency> <pectionency> <groupId> Commons-FileUpload </groupId> <artifactid> commons-fileupload </artifactid> <3.1 </dependency> </dependency> <groupid> org.springframework </groupid> <artifactid> spring-web </artifactid> <bersion> 4.0.0.release </version> </dependency> <groupdency> <groupid> org.springframework </groupId> <artifactid> spring-webmvc </artifactid> <version> 4.0.0.0.0.release> 0.0 <pectionency> <groupid> org.apache.poi </groupid> <artifactid> poi </artifactid> <bersion> 3.10.1 </version> </fectionency>
관련 처리 범주 :
(i) 컨트롤러 클래스
패키지 com.research.spring.controller; import java.io.ioexception; java.util.arraylist 가져 오기; java.util.hashmap import; Java.util.list 가져 오기; java.util.map import; 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; org.springframework.steretype.controller import; org.springframework.web.bind.annotation.requestmapping; org.springframework.web.bind.annotation.requestparam; org.springframework.web.multipart.multipartfile; org.springframework.web.servlet.modelandview import; import com.research.spring.model.userinfo; import com.research.spring.view.excelview; @controller @requestmapping ( "/file") public class filecontroller {/** * excel 파일 업로드 처리 * @param 파일 * @return */@requestmapping ( "/upload") public modelandview uploadexcel (@requestparam ( "file") multiptartfile 파일) {userinfo> list = new rateraylist <usterayfo. // 이것은 "사용자"를 포함한 파일 이름이있는 파일로 만 처리되며 템플릿은 다운로드 템플릿을 사용합니다. if (file.getoriginalFilename (). contains ( "user")) {try {work wb = new hssfworkbook (file.getInputStream ()); 시트 시트 = wb.getsheetat (0); for (int i = 1; i <= sheet.getLastrownum (); i ++) {행 행 = 시트.getrow (i); userInfo info = new userInfo (); info.setusername (row.getCell (0) .getStringCellValue ()); info.setpassword (row.getCell (1) .getStringCellValue ()); list.add (정보); }} catch (ioexception e) {e.printstacktrace (); }} modelandView mav = new ModelAndView ( "Content"); mav.addoBject ( "content", list.toString ()); 반환 mav; }/*** Excel 파일 다운로드 처리*/@requestmapping ( "/download") public modelandview downloadexcel () {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 (); 새로운 ModelAndView (VE, MAP)를 반환합니다. }}(ii) 엔티티 클래스
패키지 com.research.spring.model; public class userInfo {private String username; 개인 문자열 비밀번호; public String getUserName () {return username; } public void setusername (String username) {this.username = username; } public String getPassword () {return password; } public void setpassword (문자열 비밀번호) {this.password = password; } @override public String toString () {return "userInfo [username =" + username + ", password =" + password + "]; }}(iii) 클래스보기
이 클래스는 다운로드 할 때 사용되며 봄에 페이지를 렌더링 할 때 사용자 정의 뷰 클래스를 사용하여 Excel 관련 처리를 수행합니다.
패키지 com.research.spring.view; import java.io.outputStream; import java.net.urlencoder; Java.util.list 가져 오기; java.util.map import; 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; org.springframework.web.servlet.view.document.AbStractExcelView; import com.research.spring.model.userinfo; / ** * Excel보기 다운로드 * * @author wdmcygah * */ public class ExcelView 확장 acpractExcelView {@override protected void buildExcelDocument (map <string, object> model, hssfworkbook workbook, httpservletresponse 응답) @suppresswarnings ( "rechecked"). List <UserInfo> list = (List <UserInfo>) model.get ( "Infolist"); if (list! = null && list.size ()! = 0) {int len = list.size (); 시트 시트 = Workbook.createsheet (); // 텍스트의 첫 번째 줄 설명 행 row = sheet.createrow (0); 셀 세포 = row.createcell (0, cell.cell_type_string); cell.setCellValue ( "사용자 이름"); cell = row.createcell (1, cell.cell_type_string); cell.setCellValue ( "비밀번호"); // 다음은 (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"); 응답 .SetchAracterEncoding ( "UTF-8"); // 파일 이름은 여기에서 인코딩되어 다운로드 문자열 filename = urlencoder.encode ( "user.xls", "utf-8"); // content-disposition 속성은 응답을 다운로드하도록 설정되어 있습니다 .SetHeader ( "content-disposition", "첨부 파일; filename =" + filename); outputStream os = response.getOutputStream (); workbook.write (OS); os.flush (); os.close (); }}(iv) 기본 구성 파일
파일을 업로드 할 때는 구성 파일에서 Multipartresolver 클래스를 구성해야합니다. 구성 후 Spring은 파일을 멀티 파트 파일 객체로 자동 전달 한 다음 해당 처리를 수행 할 수 있습니다. 예를 들어, 컨트롤러 클래스를 참조하십시오.
<? xml 버전 = "1.0"alcoding = "utf-8"?> <beans xmlns = "http://www.springframework.org/schema/beans"xmlns : xsi = "http://ww.w.w3.org/2001/xmlschema-instance" xmlns : p = "http://www.springframework.org/schema/p"xmlns : context = "http://www.springframework.org/schema/mvc"xmlns : util = "http://www.springframwork.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/contet 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 "/> <ean> <property name ="viewclass "value ="org.springframework.wevert.view.jstlview ""inperatlview ""reperation " value = "/web-inf/"/> <property name = "접미사"value = ". value = "5242880000000"> </property> <!-업로드를위한 임시 경로 파일 업로드 후에는 자동으로 삭제됩니다-> <속성 이름 = "uploadtempdir"value = "upload/temp"> </beans> </beans> </beans> </beans> </beans> </bean
(v) 테스트 페이지
<html> <head> <meta http-equiv = "content-type"content = "text/html; charset = utf-8"/> </head> <body> <h3> 다운로드 Excel 함수 테스트 </h3> <form action = "file/download.htm"EncType = "multiptart/form-data"method = <input = "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> <input> <value ="value = "upload excel>
전체 소스 코드를 보려면 내 Github 저장소에서 확인할 수 있습니다. 그중에서도 파일을 업로드하면 다운로드 템플릿을 충족하는 파일 만 처리합니다. 다른 파일을 처리하려면 직접 구현해야합니다. 코드 테스트는 오류없이 전달되었습니다.
위는이 기사의 모든 내용입니다. 모든 사람의 학습에 도움이되기를 바랍니다. 모든 사람이 wulin.com을 더 지원하기를 바랍니다.