A menudo encuentro la necesidad de importar y exportar Excel en el trabajo. Tengo un breve ejemplo de respuesta para compartir con usted.
No digas muchas tonterías,
1. Paquete jar requerido:
2. Código de front-end:
ieport.jsp:
<%@page import = "java.util.date"%> <%@page lenguaje = "java" contentType = "text/html; charset = utf-" pageEncoding = "utf-"%> <! DocType html público "-// wc // dtd xhtml. Transición // en" "" "" "" "http://www.w.org/tr/xhtml/dtd/xhtml-transicional.dtd"> <html xmlns = "http://www.w.org//xhtml"> <Head> <meta http-equiv = "content-type" content = "text/html"; /> <title> import/exportar página </title> <script type = "text/javascript"> function exportFile () {window.location.href = "<%= request.getContextPath ()%>/export.go"; } </script> </head> <body> <form de acción = "import.go" método = "post" enctype = "multipart/form-data"> archivo: <input type = "file" name = "uploadfile"/> <br> </br> <input type = "subt" value = "import"/> <input type = "bootin" valor = "export" oncclick = "exportfile ()") </html>Success.jsp:
<%@ page lenguaje = "java" contentType = "text/html; charset = utf-" pageEncoding = "utf-"%> <%@ taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core"%> <! doctype html público "-//wc // dtdm. Transitional // en "" http://www.w.org/tr/xhtml/dtd/xhtml-transitional.dtd "> <html xmlns =" http://www.w.org//xhtml "> <Head> <Meta http-equiv =" Content-type "Content. charset = utf- "/> <title> Página de éxito </title> <script type =" text/javascript "> // var secuserList = '$ {SecuserList}'; // alerta (SecuserList); </script> </head> <body> <c: if test = "$ {type == 'import'}"> <div> Importar con éxito! </div> <c: foreach elementos = "$ {secuserList}" var = "secuser"> <div> id: $ {secuser.userid} | name: $ {secuser.username} | contraseña: $ {secuSer.userpassword} </div> </c: foreach> </c: if> <c: test = "$ {type ' <div> Exportación con éxito! </div> </c: if> </body> </html>3. Código de fondo:
controlador:
paquete com.controller; import java.io.file; import java.util.list; import javax.annotation.resource; import javax.servlet.http.httpservletRequest; import javax.servlet.http.httpservletResponse; importar org.springframework.stereotype.controller; importar org.springframework.web.bind.annotation.requestMapping; importar org.springframework.web.bind.annotation.requestparam; importar org.springframework.web.multipart.multipartfile; importar org.springframework.web.servlet.modelandview; import com.domain.secuser; import com.service.ieportservice; @Controller Class Public IEPortController {@Resource Private IEPortService iePortService; @RequestMapping ("/import") public ModelAndView importFile (@RequestParam (value = "uploadFile") mfile mfile, httpservletRequest request, httpServletResponse Response) {String rootPath = request.getSession (). GetServletContext (). Lista <Secuser> SecuserList = IeportService.ImportFile (mfile, rootPath); ModelandView mv = new ModelAndView (); mv.addoBject ("type", "import"); MV.AdDObject ("SecuserList", SecuserList); MV.SetViewName ("/Success"); regresar MV; } @RequestMapping ("/export") public ModelAndView ExportFile (httpServletResponse Respuesta) {iePortService.ExportFile (respuesta); ModelandView mv = new ModelAndView (); MV.AdDObject ("Tipo", "Exportar"); MV.SetViewName ("/Success"); regresar MV; }} servicio:
paquete com.service; import java.io.file; import java.io.fileInputStream; import java.io.inputstream; import java.io.outputstream; import java.net.urlencoder; import java.text.simpledateFormat; import java.util.arrayList; import java.util.date; import java.util.list; import javax.annotation.resource; import javax.servlet.http.httpservletResponse; importar org.apache.poi.hssf.usermodel.hssfrow; importar org.apache.poi.hssf.usermodel.hssfsheet; importar org.apache.poi.hssf.usermodel.hssfworkbook; importar org.apache.poi.ss.usermodel.cellstyle; importar org.apache.poi.ss.usermodel.font; importar org.apache.poi.xssf.usermodel.xssfcell; importar org.apache.poi.xssf.usermodel.xssffont; importar org.apache.poi.xssf.usermodel.xssfrow; importar org.apache.poi.xssf.usermodel.xssfsheet; importar org.apache.poi.xssf.usermodel.xssfworkbook; importar org.springframework.stereotype.service; importar org.springframework.web.multipart.multipartfile; import com.dao.ieportdao; import com.domain.secuser; @Service Public Class IEPortService {@Resource Private IEPORTDAO IEPORTDAO; Lista pública <secuser> importFile (multipartfile mfile, string rootPath) {list <secuser> secuserList = new ArrayList <Secuser> (); Cadena filename = mfile.getOriginalFileName (); String sufix = filename.substring (filename.lastIndexOf (".") +, Filename.length ()); String ym = new SimpleDateFormat ("yyyy-mm"). Format (nueva fecha ()); Cadena filepath = "uploadFile/" + ym + nombre de archivo; intente {archivo archivo = nuevo archivo (rootpath + filepath); if (file.exists ()) {file.delete (); file.mkdirs (); } else {file.mkdirs (); } mfile.transferto (archivo); if ("xls" .equals (sufijo) || "xls" .equals (sufix)) {secuserList = importxls (archivo); ieportdao.importfile (SecuserList); } else if ("xlsx" .equals (sufijo) || "xlsx" .equals (sufix)) {secuserList = importxlsx (archivo); ieportdao.importfile (SecuserList); }} catch (Exception e) {E.PrintStackTrace (); } return SecuserList; } Lista privada <secuser> importxls (archivo de archivo) {list <secuser> secuserList = new ArrayList <Secuser> (); InputStream es = nulo; Hssfworkbook hworkbook = null; try {is = new FileInputStream (archivo); HWorkBook = nuevo 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 (Exception e) {E.PrintStackTrace (); } finalmente {if (null! = is) {try {is.close (); } catch (Exception e) {E.PrintStackTrace (); }} if (null! = hworkbook) {try {hworkbook.close (); } catch (Exception e) {E.PrintStackTrace (); }}} return SecuserList; } Lista privada <secuser> importxlsx (archivo de archivo) {list <secuser> secuserList = new ArrayList <Secuser> (); InputStream es = nulo; Xssfworkbook xworkbook = null; try {is = new FileInputStream (archivo); 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 (Exception e) {E.PrintStackTrace (); } finalmente {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 respuesta) {simpledateFormat df = new SimpledateFormat ("yyyymmdd"); OutputStream OS = NULL; Xssfworkbook xworkbook = null; Pruebe {String filename = "user" + df.format (new date ()) + ".xlsx"; OS = respuesta.getOutputStream (); respuesta.reset (); Respuesta.Setheader ("Disposición de contenido", "Adjunto; FileName =" + URLENCODER.Encode (FileName, "Utf-")); respuesta.setContentType ("Aplicación/Octet-Streem"); xworkbook = new XSSFWorkBook (); XSSFSheet xSheet = xworkbook.createSheet ("UserList"); // Establecer encabezado de la página de hoja SetsheTheTeader (Xworkbook, xsheet); // Establecer contenido de la página SetsheetContent (xworkbook, xsheet); XworkBook.Write (OS); } catch (Exception e) {E.PrintStackTrace (); } finalmente {if (null! = os) {try {os.close (); } catch (Exception e) {E.PrintStackTrace (); }} if (null! = xworkbook) {try {xworkbook.close (); } catch (Exception e) {E.PrintStackTrace (); }}}}} / ** * Establecer encabezado de la página de la hoja * @param xworkbook * @param xsheet * / private void setSheetheader (xssfworkbook xworkbook, xssfsheet xSheet) {xSheet.setColumnWidth (, *); xSheet.SetColumnWidth (, *); xSheet.SetColumnWidth (, *); CellStyle CS = XworkBook.CreateCellStyle (); // establecer centrado horizontal y vertical cs.Setalignment (CellStyle.align_center); cs.SetVerticalAlignment (CellStyle.Verical_Center); // establecer Font Font HeaderFont = XworkBook.CreateFont (); HeaderFont.SetFontheLightInPoints ((corto)); HeaderFont.SetBoldWeight (xssffont.boldweight_bold); HeaderFont.SetFontName ("安体"); cs.SetFont (HeaderFont); cs.SetWrapText (true); // es posible envolver la línea automáticamente xssfrow xrow = xSheet.Createrow (); Xssfcell xcell = xrow.createCell (); XCell.SetCellStyle (CS); xcell.setCellValue ("ID de usuario"); Xssfcell xcell = xrow.createCell (); XCell.SetCellStyle (CS); xcell.setCellValue ("Nombre de usuario"); Xssfcell xcell = xrow.createCell (); XCell.SetCellStyle (CS); xcell.setCellValue ("Password"); } / ** * Establecer contenido de la página de la hoja * @param xworkbook * @param xsheet * / private void setsheetContent (xssfworkbook xworkbook, xssfsheet xSheet) {list <secuser> secuSerList = iePortDao.getSeCuserList (); CellStyle CS = XworkBook.CreateCellStyle (); cs.SetWrapText (verdadero); if (null! = SecuserList && SecuserList.size ()>) {for (int i =; i <sechuserList.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 ()); romper; caso: xcell.setCellValue (secuser.getUsername ()); romper; caso: xcell.setCellValue (secuser.getuserpassword ()); romper; predeterminado: ruptura; }}}}}}Dao:
paquete com.dao; import java.sql.resultset; import java.sql.sqlexception; import java.util.arrayList; import java.util.list; import javax.annotation.resource; importar org.springframework.stereotype.repository; import com.domain.secuser; importar org.springframework.jdbc.core.jdbctemplate; importar org.springframework.jdbc.core.rowmapper; @Repository Public Class IEPortDao {@Resource Private JDBCTEMPLATE JDBCTEMPLATE; RowMapper privado <Secuser> surowMapper = null; Private IEportDao () {surowMapper = new RowMapper <Secuser> () {@Override public Secuser Maprow (ResultSet RS, int index) lanza SQLException {Secuser Secuser = new Secuser (); secuser.setUserID (rs.getString ("user_id")); secuser.setUsername (rs.getString ("user_name")); secuser.setUserPassword (rs.getString ("user_password")); regreso Secuser; }}; } public void importFile (list <secuser> secuserList) {try {string sql = "inserte en valores sec_user (uuid (),?,?)"; List <object []> paramslist = new ArrayList <Object []> (); para (int i =; i <secuserList.size (); i ++) {secuser secuser = secuserList.get (i); Objeto [] params = nuevo objeto [] {secuser.getUsername (), secuser.getuserpassword ()}; paramslist.add (params); } jdbctemplate.batchupdate (sql, paramslist); } catch (Exception e) {E.PrintStackTrace (); }} Lista pública <secuser> getSecuserList () {list <secuser> sulist = new ArrayList <Secuser> (); StringBuffer sb = new StringBuffer (); sb.append ("Seleccione Su.user_id, Su.user_name, su.user_password de SEC_USER SU"); intente {sulist = jdbctemplate.query (sb.toString (), surowMapper); } catch (Exception e) {E.PrintStackTrace (); } return sulist; }}dominio:
paquete com.domain; Public Class Secuser {String UserId; // nombre de usuario de cadena de identificación de usuario; // Nombre de usuario String UserPassword; // Password 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. Archivo de configuración:
<? xml versión = "." encoding = "utf-"?> <web-app xmlns: xsi = "http://www.w.org//xmlschema-instance" xmlns = "http://java.sun.com/xml/ns/Javaee" xsi: schemalocation = "http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/Javaee/web-app__.xsd" id = "Webapp_id" <Splay-Name> SpringsPringMvCpoi </siplip-name> <Welcome-file-list> <Devenido-File> iePort.jsp </Welcome-File> </Welcome-File-List> <!-Especifique el nombre y la ubicación del archivo de configuración de Spring-> <context-param> <amamname-name> contextconfiglocation </param-name> <amarr-value> Classpath: Application-contex classpath: dataSource-context.xml </param-value> </context-param> <!-Configurar el oyente-> <siader> <searcher-class> org.springframework.web.context.contextloaderListener </oficer-classhass> </oyear> < <Servlet-name> DispatcherServlet </servlet-name> <ervlet-class> org.springframework.web.servlet.dispatcherservlet </servlet-class> <!-Configurar la ubicación del archivo de configuración de SpringMVC-> <Init-Param> <amamname-name> contextconfiglocation </param-name> <comam-value> classpath: spring-mvc.mvc.mvath </paramvale> </init-param> </servlet> <servlet-mapping> <servlet-name> despachadorServlet </servlet-name> <url-pattern>*. Go </url-pattern> </servlet-mapping> <!-Codificación de archivo de archivo para evitar el código de acumulación-> <filter> <filter-name> CaracteriCodingFilter </filter-name> <filter-class> org.springframework.web.filter.characteriCoDingFilter </filter-class> <it-param> <amamname> codificación </param-name> <amam-value> UTF-</am-value> </initparam> </filtre> <filter-mapping> <filter-name> carácter> <URL-Pattern>/*</url-Pattern> </filter-mapping> </beb-app>
<? xml versión = "." 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.org/schem 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-..xsd http://www.springframework.org/schema/context http://www.springingwork.org/schema/context/spring-conte-conte-..xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-..xsd http://www.springframework.org/ http://www.springframework.org/schema/aop/spring-aop-..xsd "> <!-Configurar paquetes de escaneo automático-> <context: component-scan base-package =" com.controller "> </context: component-scan> <!-configure springmvc springmvc's resuelve-> <<riptroller" n. valor = "/web-inf/vistas/"> </propiedad> <propiedad name = "suffix" value = ". jsp"> </property> </bean> <!-admitir la carga de archivos-> <bean id = "multipartresolver"/> </les>
<? xml versión = "." 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/schema/sbeans/spring-spring-beat-beans-beans-beans http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-..xsd "> <context: component-scan base-package =" com "> </context: componente>
<? xml versión = "." 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/schema/scoans/spring-ste http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd "> <!-Lea el archivo de configuración de JDBC-> <contextion-contexture ubicación =" classpath: jdbc.properties "<! <bean id="dataSource" destroy-method="close"> <property name="user" value="${jdbc.user}"></property> <property name="password" value="${jdbc.password}"></property> <property name="driverClass" value="${jdbc.driverClass}"></property> <property name="jdbcUrl" value = "$ {jdbc.jdbcurl}"> </property> <!-Cuando se usan las conexiones en el grupo de conexiones, el número de nuevas conexiones creadas a la vez por cp-> <propiedad name = "adquirincrement" valor = ""> </propiedad> <!-El número de conexiones creadas durante la inicialización debe estar entre minpoolsize y maxPoolsize-> <nombre de propiedad "=" Nombre de propiedad ". value = ""> </property> <Property name = "maxpoolSize" value = ""> </property> <Property name = "minpoolSize" value = ""> </property> <Property name = "maxconnectionAge" value = ""> </property> <Property name = "maxidletEtime" value = ">" </propiets> <sperty name = "maxidletImeexcessEssEntections" value "value"> "</d. <Property name = "testConnectionOncheckout" value = "false"> </propine> <Property name = "testConnectionOnCheckin" value = "false"> </property> <!-Verifique las conexiones inactivas en el grupo de conexión cada segundo-> <Property name = "idleconnectionTperiod" Value = ""> </propiedad> <name de propiedad = "name de propiedad =" Value "/" "/" "</" </"</" </"</" </"</" </"<propiedad <pertue name = "adquireretryDelay" value = ""> </propiety> <Property name = "PreferredTeStQuery" value = "Seleccionar de dual"> </property> </ bean> <!-Configurar JDBC Template jdbctemplate-> <bean id = "jdbctemplate"> <constructor-arg refinJDBC.DrivClass = com.mysql.jdbc.driver jdbc.jdbcurl = jdbc: mysql: // localhost:/mydb jdbc.user = myuser jdbc.password = myuser
5. Estructura del directorio:
6. Demostración de resultados
Importar:
Exportar:
PD:
1. Este novato, dado que aún no ha sabido cómo agregar archivos adjuntos, publica todo el código y agrega la estructura del directorio. Ella aprenderá a agregar archivos adjuntos en el futuro y luego modificarlos.
Lo anterior es todo el contenido de este artículo. Espero que sea útil para el aprendizaje de todos y espero que todos apoyen más a Wulin.com.