実際のアプリケーションでは、多くの場合、この問題に対処するために、データのインポート、統計のダウンロードなど、Excelがアップロードまたはダウンロードされている状況に遭遇することがよくあります。Excelの処理がApacheのPOIコンポーネントを使用するSpringMVCに基づいて、簡単なアップロードダウンロード例を書きました。
主な依存関係は次のとおりです。
<Dependency> GroupId> commons-io </groupid> <artifactid> commons-io </artifactid> <version> 2.4 </version> </dependency> <expendency> commons-fileupload </groupid> <artifactid> commons-fileupload </desopactid> <groupId> org.springframework </groupid> <artifactid> spring-web </artifactid> <version> 4.0.0.release </version> </dependency> <dependency> groupid> org.springframework </groupid> <artifactid> spring-webmvc </verions> <Dependency> groupId> org.apache.poi </groupId> <artifactid> poi </artifactid> <version> 3.10.1 </version> </dependency>
関連処理カテゴリ:
(i)コントローラークラス
パッケージcom.research.spring.controller; java.io.ioexceptionをインポートします。 java.util.arraylistをインポートします。 java.util.hashmapをインポートします。 java.util.listをインポートします。 java.util.mapをインポートします。 org.apache.poi.hssf.usermodel.hssfworkbookをインポートします。 org.apache.poi.ss.s.usermodel.rowをインポートします。 org.apache.poi.ss.s.usermodel.sheetをインポートします。 Import org.apache.poi.ss.s.usermodel.workbook; org.springframework.stertype.controllerをインポートします。 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; com.research.spring.model.userinfoをインポートします。 com.research.spring.view.excelviewをインポートします。 @Controller @RequestMapping( "/file")public class filecontroller {/** * excel file upload processing * @param file * @return */@RequestMapping( "/upload")public model andview uploadexcel(@requestparam( "file")multipartfileファイル) //これは「ユーザー」を含むファイル名を持つファイルでのみ処理され、テンプレートはダウンロードテンプレートを使用します(file.getoriginalFileName()。シートシート= 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()); 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(){パスワードを返します。 } public void setPassword(string password){this.password = password; } @Override public string toString(){return "userinfo [username =" + username + "、password =" + password + "]"; }}(iii)クラスを表示します
このクラスは、ダウンロードするときに使用され、春にページをレンダリングするときに、カスタムビュークラスを使用してExcel関連の処理を実行します。
パッケージcom.research.spring.view; java.io.outputStreamをインポートします。 java.net.urlencoderをインポートします。 java.util.listをインポートします。 java.util.mapをインポートします。 javax.servlet.http.httpservletrequestをインポートします。 javax.servlet.http.httpservletResponseをインポートします。 org.apache.poi.hssf.usermodel.hssfworkbookをインポートします。 org.apache.poi.ss.s.usermodel.cellをインポートします。 org.apache.poi.ss.s.usermodel.rowをインポートします。 org.apache.poi.ss.s.usermodel.sheetをインポートします。 org.springframework.web.servlet.view.document.abstractexcelview; com.research.spring.model.userinfoをインポートします。 / ** * Excel Viewをダウンロード * * @author wdmcygah * */ public class excelview extends abstractexcelview {@override Protected void buildexceldocument(map <string、object> model、hssfworkbook workbook、httpservletrequest request、httpservletresponse response) List <userininfo> list =(list <userininfo>)model.get( "infolist"); if(list!= null && list.size()!= 0){int len = list.size();シートシート= workbook.createsheet(); //テキストの最初の行説明行row = sheet.createrow(0); Cell cell = row.createcell(0、cell.cell_type_string); cell.setCellValue( "username"); cell = row.createcell(1、cell.cell_type_string); cell.setCellValue( "Password"); //以下は(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()); }} respons.setContentType( "Application/vnd.ms-excel"); Response.setcharacterencoding( "utf-8"); //ファイル名はここにエンコードされており、ダウンロード中に漢字が正常に表示されることを確認しますstring filename = urlencoder.encode( "user.xls"、 "utf-8"); // content-dispositionプロパティは、respons.setheader( "content-disposition"、 "attachment; filename =" + filename)をダウンロードするように設定されています。 outputStream os = response.getOutputStream(); workbook.write(os); os.flush(); os.close(); }}(iv)メイン構成ファイル
ファイルをアップロードするときは、構成ファイルでMultiPartresolverクラスを構成する必要があります。構成後、SpringはファイルをMultiPartFileオブジェクトに自動的に渡し、対応する処理を実行できます。たとえば、コントローラークラスを参照してください。
<?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/mvc" xmlns:util = "http://www.springframework. xsi:schemalocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www. 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> value = "/web-inf/"/> <プロパティname = "suffix" value = "。JSP"/> </bean> <! - ファイルパーサー設定をアップロード - > <bean id = "multipartresolver"> <プロパティ名= "defaultencoding" value = "utf-8"> </<! value = "52428880000000"> </property> <! - ファイルをアップロードする一時的なパス、アップロード後に自動的に削除されます - > <プロパティname = "uploadtempdir" value = "upload/temp"> </property> </bean> </beans>
(v)テストページ
<html> <head> <メタhttp-equiv = "content-type" content = "text/html; charset = utf-8"/> </head> <body> <h3>ダウンロードExcel関数をテスト</h3> <form action = "file/download.htm" enctype = " excel "> </input> </form> <h3>アップロードExcel関数をテスト</h3> <form action =" file/upload.htm "enctype =" multipart/form-data "method =" post "> <input type =" file "file"> "file"> </input> <入力タイプ= "
完全なソースコードを表示したい場合は、GitHubリポジトリで確認できます。その中で、ファイルをアップロードすると、ダウンロードテンプレートを満たすファイルを処理します。他のファイルを処理するには、自分で実装する必要があります。コードテストはエラーなしで合格しました。
上記はこの記事のすべての内容です。みんなの学習に役立つことを願っています。誰もがwulin.comをもっとサポートすることを願っています。