職場でExcelをインポートしてエクスポートする必要性に遭遇することがよくあります。私はあなたと共有するための簡単な答えの例を持っています。
ナンセンスをあまり言わないでください、
1。必要な瓶パッケージ:
2。フロントエンドコード:
ieport.jsp:
<%@page Import = "Java.util.date"%> <%@page Language = "java" contentType = "text/html; charset = utf-" pageencoding = "utf-"%> <!doctype html public " - // wc // dtd xhtml。 "http://www.w.org/tr/xhtml/dtd/xhtml-transitional.dtd"> <html xmlns = "http://www.w.org//xhtml" charset = utf- "/> <title>インポート/エクスポートページ</title> <script type =" text/javascript "> function exportfile(){window.location.href =" <%= request.getContextPath()%>/export.go "; } </script> </head> <body> <form action = "import.go" method = "post" enctype = "multipart/form-data"> file:<入力タイプ= "ファイル" name "name =" uploadfile "/> <br> </br> <入力タイプ="送信 "値=" Import "/> <input =" "/> </html>success.jsp:
<%@ページ言語= "java" contentType = "text/html; charset = utf-" pageencoding = "utf-"%> <%@ taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core"%> <! Transitional // en "" http://www.w.org/tr/xhtml/dtd/xhtml-transitional.dtd "> <html xmlns =" http://www.w.org//xhtml "> content = "text/html; charset = utf-"/> <title> success page </title> <script type = "text/javascript"> // var secuserlist = '$ {secuserlist}'; // alert(secuserList); </script> </head> <body> <c:test = "$ {type == 'import'}"> <div> Importは正常に! </div> <c:foreach items = "$ {secuserlist}" var = "secuser"> <div> id:$ {secuser.userid} | name:$ {secuser.username} | $ {secuser.userpassword} $ {secuser.userpassword} </div> </c: "> < <div>エクスポートに正常に! </div> </c:if> </body> </html>3。背景コード:
コントローラ:
パッケージcom.controller; java.io.fileをインポートします。 java.util.listをインポートします。 javax.annotation.resourceをインポートします。 javax.servlet.http.httpservletrequestをインポートします。 javax.servlet.http.httpservletResponseをインポートします。 org.springframework.stereotype.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.domain.secuserをインポートします。 com.service.ieportserviceをインポートします。 @Controller Public Class IEPORTCONTROLLER {@Resource Private IEPORTSERVICE IEPORTSERVICE; @RequestMapping( "/import")Public ModelandView ImportFile(@RequestParam(value = "UploadFile")MultiPartFile Mfile、httpservletrequest Request、httpservletResponse Response){string rootpath = request.getsession()。getRealPath()。リスト<Secuser> secuserList = ieportservice.importfile(mfile、rootpath); ModelAndView MV = new ModelAndView(); mv.addobject( "type"、 "Import"); mv.addobject( "secuserList"、secuserList); mv.setViewName( "/success"); MVを返します。 } @RequestMapping( "/export")public modelandview exportfile(httpservletResponse応答){ieportservice.exportfile(response); ModelAndView MV = new ModelAndView(); mv.addobject( "type"、 "export"); mv.setViewName( "/success"); MVを返します。 }}サービス:
パッケージcom.service; java.io.fileをインポートします。 java.io.fileinputStreamをインポートします。 java.io.inputStreamをインポートします。 java.io.outputStreamをインポートします。 java.net.urlencoderをインポートします。 java.text.simpledateformatをインポートします。 java.util.arraylistをインポートします。 Import Java.util.date; java.util.listをインポートします。 javax.annotation.resourceをインポートします。 javax.servlet.http.httpservletResponseをインポートします。 org.apache.poi.hssf.usermodel.hssfrowをインポートします。 org.apache.poi.hssf.usermodel.hssfsheetをインポートします。 org.apache.poi.hssf.usermodel.hssfworkbookをインポートします。 org.apache.poi.ss.s.usermodel.cellstyleをインポートします。 org.apache.poi.ss.s.usermodel.fontをインポートします。 org.apache.poi.xssf.usermodel.xssfcellをインポートします。 org.apache.poi.xssf.usermodel.xssffontをインポートします。 org.apache.poi.xssf.usermodel.xssfrowをインポートします。 org.apache.poi.xssf.usermodel.xssfsheetをインポートします。 org.apache.poi.xssf.usermodel.xssfworkbookをインポートします。 org.springframework.stereotype.serviceをインポートします。 Import org.springframework.web.multipart.multipartfile; com.dao.ieportdaoをインポートします。 com.domain.secuserをインポートします。 @Service Public Class IEPORTSERVICE {@Resource Private IEPORTDAO IEPORTDAO;パブリックリスト<Secuser> ImportFile(MultiPartFile MFile、String rootPath){List <Secuser> secuserList = new ArrayList <Secuser>();文字列filename = mfile.getoriginalfilename(); string suffix = filename.substring(filename.lastindexof( "。") +、filename.length()); string ym = new SimpledateFormat( "yyyy-mm")。format(new date()); string filepath = "uploadfile/" + ym + filename; try {file file = new file(rootpath + filepath); if(file.exists()){file.delete(); file.mkdirs(); } else {file.mkdirs(); } mfile.transferto(file); if( "xls" .equals(suffix)|| "xls" .equals(suffix)){secuserlist = importxls(file); ieportdao.importfile(secuserlist); } else if( "xlsx" .equals(suffix)|| "xlsx" .equals(suffix)){secuserlist = importxlsx(file); ieportdao.importfile(secuserlist); }} catch(例外e){e.printstacktrace(); } secuserListを返します。 } private list <Secuser> importxls(file file){list <secuser> secuserList = new ArrayList <Secuser>(); inputstream is = null; hssfworkbook hworkbook = null; try {is = new fileInputStream(file); hworkbook = new hssfworkbook(is); hssfsheet hsheet = hworkbook.getsheetat(); if(null!= hsheet){for(int i =; i <hsheet.getPhysicalNumberOfRows(); i ++){secuser su = new secuser(); hssfrow hrow = hsheet.getrow(i); su.setUsername(hrow.getCell()。toString()); su.setuserpassword(hrow.getCell()。toString()); secuserlist.add(su); }}} catch(例外e){e.printstacktrace(); }最後に{if(null!= is){try {is.close(); } catch(Exception e){e.printstacktrace(); }} if(null!= hworkbook){try {hworkbook.close(); } catch(Exception e){e.printstacktrace(); }}} return secuserList; } private list <secuser> importxlsx(file file){list <secuser> secuserList = new ArrayList <Secuser>(); inputstream is = null; xssfworkbook xworkbook = null; try {is = new fileInputStream(file); xworkbook = new xssfworkbook(is); XSSFSHEET XSHEET = XWORKBOOK.GETSHEETAT(); if(null!= xsheet){for(int i =; i <xsheet.getPhysicalNumberOfRows(); i ++){secuser su = new secuser(); XSSFROW XROW = XSHEET.GETROW(I); su.setusername(xrow.getCell()。toString()); su.setuserpassword(xrow.getCell()。toString()); secuserlist.add(su); }} catch(例外e){e.printstacktrace(); }最後に{if(null!= is){try {is.close(); } catch(Exception e){e.printstacktrace(); }} if(null!= xworkbook){try {xworkbook.close(); } catch(Exception e){e.printstacktrace(); }}} return secuserList; } public void exportfile(httpservletResponse応答){simpledateFormat df = new simpledateFormat( "yyyymmdd"); outputStream os = null; xssfworkbook xworkbook = null; try {string filename = "user" + df.format(new date()) + ".xlsx"; os = response.getOutputStream(); Response.reset(); Response.setheader( "content-disposition"、 "attachment; filename =" + urlencoder.encode(filename、 "utf-")); Response.setContentType( "Application/Octet-Streem"); xworkbook = new xssfworkbook(); XSSFSHEET XSHEET = XWORKBOOK.CREATESHEET( "UserList"); //シートページヘッダーSetSheEtheader(XWorkBook、Xsheet)を設定します。 //シートページコンテンツSetSheetContent(XWorkBook、Xsheet)を設定します。 xworkbook.write(os); } catch(Exception e){e.printstacktrace(); }最後に{if(null!= os){try {os.close(); } catch(Exception e){e.printstacktrace(); }} if(null!= xworkbook){try {xworkbook.close(); } catch(Exception e){e.printstacktrace(); }}}}} / ** * SETシートページヘッダー * @Param XWorkBook * @Param Xsheet * / private void setsheetheader(xssfworkbook xworkbook、xssfsheet xsheet){xsheet.setcolumnwidth(、 *); xsheet.setColumnWidth(、 *); xsheet.setColumnWidth(、 *); CellStyle CS = XWorkBook.CreateCellStyle(); //水平および垂直センターのセットCs.SetAlignment(cellStyle.Align_Center); cs.setverticalAlignment(cellstyle.vertical_center); //フォントフォントheaderfont = xworkbook.createfont(); headerfont.setfontheightinpoints((short)); headerfont.setboldweight(xssffont.boldweight_bold); headerfont.setFontName( "安体"); cs.setfont(headerfont); cs.setWraptext(true); //ラインを自動的に包むことは可能ですかxssfrow xrow = xsheet.createrow(); XSSFCELL XCELL = XROW.CREATECELL(); xcell.setcellstyle(cs); xcell.setCellValue( "ユーザーID"); XSSFCELL XCELL = XROW.CREATECELL(); xcell.setcellstyle(cs); xcell.setCellValue( "ユーザー名"); XSSFCELL XCELL = XROW.CREATECELL(); xcell.setcellstyle(cs); xcell.setCellValue( "Password"); } / ** *シートページのセットコンテンツ * @param xworkbook * @param xsheet * / private void setsheetcontent(xssfworkbook xworkbook、xssfsheet xsheet){list <secuser> secuserlist = ieportdao.getsecuserlist(); CellStyle CS = XWorkBook.CreateCellStyle(); cs.setWraptext(true); if(null!= secuserlist && secuserlist.size()>){for(int i =; i <secuserlist.size(); i ++){xssfrow xrow = xsheet.createrow(i+); secuser secuser = secuserlist.get(i); for(int j =; j <; j ++){xssfcell xcell = xrow.createcell(j); xcell.setcellstyle(cs); switch(j){case:xcell.setcellvalue(secuser.getuserid());壊す;ケース:xcell.setCellValue(secuser.getUsername());壊す;ケース:xcell.setCellValue(secuser.getUserPassWord());壊す;デフォルト:break; }}}}}}ダオ:
パッケージcom.dao; java.sql.resultsetをインポートします。 java.sql.sqlexceptionをインポートします。 java.util.arraylistをインポートします。 java.util.listをインポートします。 javax.annotation.resourceをインポートします。 Import org.springframework.stereotype.repository; com.domain.secuserをインポートします。 org.springframework.jdbc.core.jdbctemplateをインポートします。 org.springframework.jdbc.core.rowmapperをインポートします。 @Repository Public Class IEPORTDAO {@Resource Private JDBCTEMPLATE JDBCTEMPLATE; private rowmapper <secuser> surowmapper = null; private iEportdao(){surowmapper = new rowmapper <secuser>(){@override public secuser maprow(resultset rs、int index)throws sqlexception {secuser secuser = new secuser(); secuser.setuserid(rs.getString( "user_id")); secuser.setUsername(rs.getString( "user_name")); secuser.setuserpassword(rs.getString( "user_password")); Return Secuser; }}; } public void importfile(list <secuser> secuserList){try {string sql = "sec_user値(uuid()、?、?)"に挿入list <object []> paramslist = new ArrayList <object []>(); for(int i =; i <secuserlist.size(); i ++){secuser secuser = secuserlist.get(i); object [] params = new object [] {secuser.getusername()、secuser.getuserpassword()}; paramslist.add(params); } jdbctemplate.batchupdate(sql、paramslist); } catch(Exception e){e.printstacktrace(); }} public list <Secuser> getSecuserList(){list <secuser> sulist = new ArrayList <Secuser>(); stringbuffer sb = new StringBuffer(); sb.append( "Select Su.User_id、su.user_name、su.user_password from sec_user su"); try {sulist = jdbctemplate.query(sb.tostring()、surowmapper); } catch(Exception e){e.printstacktrace(); } ulistを返します。 }}ドメイン:
パッケージcom.domain; Public Class Secuser {string userid; //ユーザーID文字列ユーザー名; // username string userpassword; //パスワードpublic string getUserid(){return userid; } public void setuserid(string userid){this.userid = userid; } public String getUserPassWord(){return userPassword; } public void setuserpassword(string userpassword){this.userpassword = userpassword; } public string getUsername(){return username; } public void setUsername(string username){this.username = username; }}4。構成ファイル:
<?xmlバージョン= "。" encoding = "utf - "?> <web-app xmlns:xsi = "http://www.w.org//xmlschema-instance" xmlns = "http://java.sun.com/xml/ns/javaeee" xsi:schemalocation = "http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/ns/javaee/web-app__.xdd" ">" "> <displaing-name> springspringmvcpoi </display-name> <welcome-file-list> <welcome-file> ieport.jsp </welcome-file> </welcome-file-list> <! - spring構成ファイルの指定 - > <コンテキスト-param> <param-name> contextconfiglocoti classPath:dataSource-context.xml </param-value> </context-param> <! - configure ristener-> <リスナー> <リスナークラス> org.springframework.web.context.contextloaderlistener </ristener-class> </siender> <! <Servlet-Name> DispatcherServlet </servlet-name> <servlet-class> org.springframework.web.servlet.dispatcherservlet </servlet-class> <! - springmvcの構成ファイルの構成 - > <init-param> <param-name> contextconfiglocotion </param-name> <pram-name> <param-name> <param-value> </init-param> </servlet> <servlet-mapping> <servlet-name> dispatcherservlet </servlet-name> <url-pattern>*。go</url-pattern> </servlet-mapping> <! - ターボードコードを防ぐためのアップロードファイルエンコード - > <フィルター> <フィルター> <フィルター> <フィルター - フィルター - 版画ファイル</フィルター賞> <filter-class> org.springframework.web.filter.characterencodingfilter </filter-class> <init-param> <param-name>エンコード</param-name> <param-value> utf- </parm-value> </init-param> </filter> <filter-name> <filter-name> <filter-name> <filter-name> </filter-filting> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
<?xmlバージョン= "。" encoding = "utf - "?> <beans xmlns = "http://www.springframework.org/schema/beans" xmlns:xsi = "http://www.w.org//xmlschema-instance" " xmlns:p = "http://www.springframework.org/schema/p" xmlns:context = "http://www.springframework.org/schema/aop" xmlns:tx = "http://www.springframework. XMLNS:MVC = "http://www.springframework.org/schema/mvc" xmlns:util = "http://www.springframework.org/schema/util" xsi:schemalocation = " http://www.springframework.org/schema/beans/spring-beans-..xd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-...xcont-context-...xcont-contex http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-..xsd http://www.springframework.org/schema/ap http://www.springframework.org/schema/aop/spring-aop-..xsd "> <! - 自動スキャンパッケージ - > <コンテキスト:Com.Controller" com.Controller "> </context:Component-Scan> <! value = "/web-inf/views/"> </property> <property name = "suffix" value = "。jsp"> </property> </bean> <! - ファイルのアップロードをサポート - > <bean id = "multipartresolver"/> </bean> </beans>
<?xmlバージョン= "。" encoding = "utf - "?> <beans xmlns = "http://www.springframework.org/schema/beans" xmlns:xsi = "http://www.w.org//xmlschema-instance" " xmlns:Context = "http://www.springframework.org/schema/context" xsi:schemalocation = "http://www.springframework.org/schema/beans http://www.springframework.org.org/schema/spring/spring/ http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-..xsd "> <コンテキスト:Component-scan base-package =" com "> <
<?xmlバージョン= "。" encoding = "utf - "?> <beans xmlns = "http://www.springframework.org/schema/beans" xmlns:xsi = "http://www.w.org//xmlschema-instance" " xmlns:context = "http://www.springframework.org/schema/context" xsi:schemalocation = "http://www.springframework.org/schema/beans http://www.springframework.orgwork.org/schems.spring/ http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd "> <! - 読み取りJDBC構成ファイル - >ソース - > <bean id = "dataSource" Destroy-method = "close"> <property name = "user" value = "$ {jdbc.user}"> </property name = "password" value = "{jdbc.password} name = "jdbcurl" value = "$ {jdbc.jdbcurl}"> </property> <! - 接続プールの接続が使い果たされると、CPによって一度に作成された新しい接続の数 - > <プロパティname = "quickireincrement" value = "" "> </propertiationの数は、初期化の間に作成されなければなりません。 name = "initialpoolsize" value = ""> </property> <property name = "maxpoolsize" value = ""> </property name> <property name = "minpoolsize" balue = ""> </property name> <property name = "maxconnectionage" value = ""> </property name = "maxidletime" name = "maxidletimeexcessconnections" value = ""> </property> <property name = "testConnectionOnCheckout" value = "false"> </property> <プロパティ名= "testConnectionOnCheckin" value = "false"> </property> < name = "Acquireretryattempts" value = ""> </property name = "accoireretrydelay" value = "" "> </property name =" fromedtestquery "value =" select from dual "> </property> </bean> <! ref = "dataSource"> </constructor-arg> </bean> </bean>jdbc.driverclass = com.mysql.jdbc.driver jdbc.jdbcurl = jdbc:mysql:// localhost:/mydb jdbc.user = myuser jdbc.password = myuser
5。ディレクトリ構造:
6。結果のデモ
輸入:
輸出:
PS:
1.この初心者は、添付ファイルを追加する方法をまだ知られていないため、すべてのコードを投稿し、ディレクトリ構造を追加します。彼女は将来添付ファイルを追加し、それらを変更する方法を学びます。
上記はこの記事のすべての内容です。みんなの学習に役立つことを願っています。誰もがwulin.comをもっとサポートすることを願っています。