Я часто сталкиваюсь с необходимостью импорта и экспорта 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"> <Head> <meta http-equiv = "content-tont" content "; /> <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"> файл: <input type = "file" name = "uploadfile"/> <br> </br> <input type = "value =" import "/> <inport =" value = "export" onclick = "/> export"/> export "/> export"/> "/> <>>"/> "/force"/value ". </html>Успех.jsp:
<%@ page language = "java" contentType = "text/html; charset = utf-" pageencoding = "utf-"%> <%@ taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core"%> <! Doctype html public ". Transitional // en "" http://www.w.org/tr/xhtml/dtd/xhtml-transitional.dtd "> <html xmlns =" http://www.w.org//xhtml "> <Head> <Meta http-equiv =" content-tempe = content- "/content-equiv =" content-teml " charset = utf- "/> <title> страница успеха </title> <script type =" text/javascript "> // var secuserlist = '$ {secuserlist}'; // предупреждение (secuserlist); </script> </head> <body> <c: if test = "$ {type == 'import'}"> <div> Импорт успешно! </div> <C: foreach items = "$ {secuserlist}" var = "secuser"> <div> id: $ {secuser.userid} | Имя: $ {secuser.username} | Пароль: $ {secuser.userPassword} </div> </c: foreach> </c: if> <c 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; Import org.springframework.sterotype.controller; Импорт org.springframework.web.bind.annotation.requestmapping; Импорт org.springframework.web.bind.annotation.requestparam; Импорт org.springframework.web.multipart.multipartfile; Импорт 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") MultiplaartFile MFILE, httpservlectrequest, httpservletresponse response) {string root root List <secuser> secuserlist = ioportservice.importfile (mfile, rootpath); ModelAndView MV = New ModelAndView (); mv.addobject ("type", "import"); mv.addobject ("secuserlist", secuserlist); mv.setViewName ("/успех"); вернуть MV; } @RequestMapping ("/export") public modelAndview ExportFile (httpservletresponse) {ioportService.exportfile (response); ModelAndView MV = New ModelAndView (); mv.addobject ("type", "Export"); mv.setViewName ("/успех"); вернуть MV; }} услуга:
пакет com.service; Импорт java.io.file; импортировать java.io.fileinputstream; импортировать java.io.inputstream; импортировать java.io.outputstream; импортировать java.net.urlencoder; импортировать java.text.simpledateformat; импортировать java.util.arraylist; импортировать java.util.date; импортировать java.util.list; Импорт javax.annotation.resource; Импорт javax.servlet.http.httpservletresponse; Import org.apache.poi.hssf.usermodel.hssfrow; Import org.apache.poi.hssf.usermodel.hssfsheet; Import org.apache.poi.hssf.usermodel.hssfworkbook; Импорт org.apache.poi.ss.usermodel.cellstyle; Импорт org.apache.poi.ss.usermodel.font; Импорт org.apache.poi.xssf.usermodel.xssfcell; Импорт org.apache.poi.xssf.usermodel.xssffont; Импорт org.apache.poi.xssf.usermodel.xssfrow; Import org.apache.poi.xssf.usermodel.xssfsheet; Import org.apache.poi.xssf.usermodel.xssfworkbook; Импорт org.springframework.stereotype.service; Импорт org.springframework.web.multipart.multipartfile; Импорт com.dao.ieportdao; Импорт com.domain.secuser; @Service public class ieportservice {@resource private ieportdao ieportdao; public List <secuser> importFile (MultipArtFile MFILE, String RootPath) {List <Secuser> secuserList = new ArrayList <SecUser> (); String 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 (суффикс) || "xls" .equals (суффикс)) {secuserlist = importxls (file); ieportdao.importfile (secuserlist); } else if ("xlsx" .equals (суффикс) || "xlsx" .equals (суффикс)) {secuserlist = importxlsx (file); ieportdao.importfile (secuserlist); }} catch (Exception e) {e.printstackTrace (); } return secuserlist; } частный список <secuser> importxls (файл файла) {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 (Exception 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; } частный список <secuser> importxlsx (файл файла) {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 (Exception 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 response) {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 ("Содержимое-распада", "ATTHAMENT; FILENAME =" + urlencoder.encode (имя файла, "utf-")); response.setContentType («Приложение/октябрь-транс»); xworkbook = new xssfworkbook (); Xssfsheet xsheet = xworkbook.createSheet ("userList"); // Установить заголовок листа SetSheTheader (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 setheetheader (xssfwork xworkbook, xssfsheet xsheet) {xsheet.setcolumnwidth (, *); xsheet.setcolumnwidth (, *); xsheet.setcolumnwidth (, *); CellStyle cs = xworkbook.createCellStyle (); // установить горизонтальный и вертикальный центрирующий CS.SetAlignment (cellStyle.align_center); cs.seterticalAlignment (cellstyle.vertical_center); // Установить шрифт font headerfont = xworkbook.createfont (); headerfont.setfontheithinpoints ((короткий)); headerfont.setboldweight (xssffont.boldweight_bold); headerfont.setFontname ("安体"); cs.setfont (headerfont); cs.setWraptext (true); // Можно ли обернуть строку автоматически xssfrow xrow = xshet.createrow (); Xssfcell xcell = xrow.createCell (); xcell.setcellstyle (CS); xcell.setCellValue ("идентификатор пользователя"); Xssfcell xcell = xrow.createCell (); xcell.setcellstyle (CS); xcell.setCellValue ("имя пользователя"); Xssfcell xcell = xrow.createCell (); xcell.setcellstyle (CS); xcell.setCellValue ("пароль"); } / ** * Содержимое страницы SET SET * @param xworkbook * @param xsheet * / private void setsheetcontent (xssfworkbook xworkbook, xssfsheet xsheet) {list <secuser> secuserlist = ioportdao.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 ()); перерыв; по умолчанию: перерыв; }}}}}}Дао:
пакет com.dao; импортировать java.sql.resultset; Импорт java.sql.sqlexception; импортировать java.util.arraylist; импортировать java.util.list; Импорт javax.annotation.resource; Import org.springframework.sterotype.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")); вернуть Secuser; }}; } public void importfile (list <secuser> secuserlist) {try {string sql = "insert in sec_user values (uuid (),?,?)"; Список <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 из sec_user su"); try {sulist = jdbctemplate.query (sb.tostring (), surowmapper); } catch (Exception e) {e.printstackTrace (); } вернуть Сулист; }}домен:
пакет com.domain; открытый класс SECUSER {String userId; // Идентификатор пользователя string string; // имя пользователя 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 version = "." 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" ids = "webapp_ vebapp_ vebapp_" vebapp_ vebapp_ ". <Slame-name> springspringmvcpoi </display-name> <selcower-file-list> <selcoveryfile> ieport.jsp </werveding-file> </werveding-file-list> <!-Укажите имя и местоположение файла конфигурации пружины-> <cestemptparam> <param-name> contextconfiglocation </param-name> <param-value> classpath: appertexmlocation </param-name> <param-value> <param-name> ClassPath: dataSource-context.xml </param-value> </context-param> <!-Настройка прослушивания-> <Learser> <lloader-class> org.springframework.web.context.contextloaderlister </sluster-class> </sluster> <!-Конфигурация Springmvc's DispatcherServelger-> <Servlet> <Servlet-name> DispatcherServlet </servlet-name> <vervlet-class> org.springframework.web.servlet.dispatcherservlet </servlet-class> <!-Конфигурировать файл конфигурации Springmvc. </init-param> </servlet> <serlet-mapping> <servlet-name> dispatcherservlet </servlet-name> <url-pattern>*. <filter-class> org.springframework.web.filter.characterencodingfilter </filter> <init-param> <param-name> кодирование </param-name> <value> utf-</param-value> </init-param> </filter-mapping> <filater-name> name> name name> hare <Url-pattern>/*</url-pattern> </filter-mapping> </web-app>
<? xml version = "." 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://wwww.springformawrame.orschema. xmlns: mvc = "http://www.springframework.org/schema/mvc" xmlns: util = "http://www.springframework.org/schema/util" xsi: schemalocation = "http://wwww.spramemema http://www.springframework.org/schema/beans/spring-beans-..xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-..xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-..xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-..xsd "> <!-Настройка автоматических сканирующих пакетов-> <Контекст: компонент-сканирование Base-package =" com.controller "> </context: component-scan> <!-Конфигурация Springmvc's View resolverter-> <bean> <bean> <bean> <bean> <bean> <bean> <bean> <bean> <bean> <bean> <bean> <bean> <bean> value = "/web-inf/views/"> </property> <name = "suffix" value = ". Jsp"> </property> </bean> <!-Поддержка загрузки файлов-> <bean id = "multipresolver"/> </beans>
<? xml version = "." 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.spramework.orgem. http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-..xsd "> <context: component-casion-package =" com "> </contune-can> </beans>
<? xml version = "." 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.spramework.org/schema/beans/springbeans.s.xspringbeansbeans.s.xspringbeans.s.xspringbeans.s.xspringbeans/springbeans.s.xspring.sspring.sspring.s.spers.springbeans/spring-beans.s.spersbemans./www.spramework. http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd "> <!-Читать файл конфигурации jdbc-> <context: property placeholder decouring =" classpath: jdbc. id = "DataSource" Drest Method = "close"> <name = "user" value = "$ {jdbc.user}"> </property> <name = "password" value = "$ {jdbc.password}"> </property> <property name = "driverclass" value = "$ {jdbc.driverclass}"> </property name> "jdbcrclass}"> </property> hame = "jdbc.driverclass}"> </property> </property> hame = "jdbc.driverclass}" value="${jdbc.jdbcUrl}"></property> <!-- When the connections in the connection pool are used up, the number of new connections created at one time by CP --> <property name="acquireIncrement" value=""></property> <!-- The number of connections created during initialization must be between minPoolSize and maxPoolSize--> <property name="initialPoolSize" value = ""> </property> <name = "maxpoolsize" value = ""> </property> <name = "minpoolsize" value = ""> </property> <name = "maxConnectionAge" value = ""> </property> <property name = "maxIdletime" value = "> </properate> <properate =" maxIdletimeex "/"/"> </properate> <properate =" maxIdletimeeme <name = "testConnectionOncheckout" value = "false"> </property> <name = "testConnectionOncheckin" value = "false"> </property> <!-Проверьте соединения на холостом ходу в пуле подключений Каждое второе-> <property name = "IdleConnectionTeStEriod" value = ""> </Properation> <Property name = "AccepateRtemptemptemptempts" value = "> </properation> <Property name =". name = "acpireretryDelay" value = ""> </property> <name = "prefendredTestQuery" value = "Выберите из двойного"> </свойство> </bean> <!-Настройка шаблона jdbc jdbctemplate-> <bean id = "jdbctemplate"> <constructor-Ar Ref = "dataSource"> <//ar-ar> </contureg> <//or-ar> </constreg> </constreg> <//jdbctemptuem </beans>jdbc.driverclass = com.mysql.jdbc.driver jdbc.jdbcurl = jdbc: mysql: // localhost:/mydb jdbc.user = myuser jdbc.password = myuser
5. Структура каталогов:
6. Демонстрация результатов
Импорт:
Экспорт:
PS:
1. Этот новичок, поскольку она еще не знала, как добавлять вложения, она публикует весь код и добавляет структуру каталогов. Она научится добавлять вложения в будущем, а затем изменить их.
Выше всего содержание этой статьи. Я надеюсь, что это будет полезно для каждого обучения, и я надеюсь, что все будут поддерживать Wulin.com больше.