ฉันมักจะต้องเผชิญกับความจำเป็นในการนำเข้าและส่งออก Excel ในที่ทำงาน ฉันมีตัวอย่างคำตอบสั้น ๆ ที่จะแบ่งปันกับคุณ
อย่าพูดเรื่องไร้สาระมาก
1. แพ็คเกจขวดที่จำเป็น:
2. รหัสส่วนหน้า:
ieport.jsp:
<%@page import = "java.util.date"%> <%@page language = "java" contentType = "ข้อความ/html; charset = utf-" pageencoding = "utf-"%> <! "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"> ไฟล์: <input type = "file" name = "uploadfile"/> <br> </br> </html>Success.jsp:
<%@ page language = "java" contentType = "ข้อความ/html; charset = utf-" pageencoding = "utf-"%> <%@ taglib คำนำหน้า = "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> หน้าความสำเร็จ </title> <script type = "text/javascript"> // var secuserlist = '$ {secuserlist}'; // Alert (secuserlist); </script> </head> <body> <c: ถ้า test = "$ {type == 'นำเข้า'}"> <div> นำเข้าสำเร็จ! </div> <c: foreach items = "$ {secuserlist}" var = "secuser"> <div> id: $ {secuser.userid} | ชื่อ: $ {secuser.username} | รหัสผ่าน: $ {secuser.user.userpassword} <div> ส่งออกได้สำเร็จ! </div> </c: ถ้า> </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; นำเข้า org.springframework.web.bind.annotation.requestparam; นำเข้า org.springframework.web.multipart.multipartfile; นำเข้า org.springframework.web.servlet.modelandview; นำเข้า com.domain.secuser; นำเข้า com.service.ieportservice; @Controller คลาสสาธารณะ ieportController {@Resource ส่วนตัว IEPORTSERVICE IEPORTSERVICE; @RequestMapping ("/นำเข้า") โมเดลสาธารณะและวิวทิวทัศน์นำเข้า (@requestParam (value = "uploadfile") multipartFile mfile, httpservletRequest Request, httpservletResponse การตอบสนอง) {string rootpath = request.getSession รายการ <secuser> secuserlist = ieportservice.importfile (mfile, rootpath); ModelAndView MV = new ModelAndView (); mv.addobject ("type", "นำเข้า"); mv.addobject ("secuserlist", secuserlist); mv.setViewName ("/ความสำเร็จ"); กลับ MV; } @RequestMapping ("/Export") Public ModelandView ExportFile (การตอบสนอง httpservletResponse) {ieportservice.exportfile (ตอบกลับ); ModelAndView MV = new ModelAndView (); mv.addobject ("type", "ส่งออก"); 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; นำเข้า org.apache.poi.hssf.usermodel.hssfrow; นำเข้า org.apache.poi.hssf.usermodel.hssfsheet; นำเข้า 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; นำเข้า org.apache.poi.xssf.usermodel.xssfsheet; นำเข้า org.apache.poi.xssf.usermodel.xssfworkbook; นำเข้า org.springframework.stereotype.service; นำเข้า org.springframework.web.multipart.multipartfile; นำเข้า com.dao.ieportdao; นำเข้า com.domain.secuser; @Service ชั้นเรียนสาธารณะ ieportservice {@Resource ส่วนตัว ieportdao ieportdao; รายการสาธารณะ <Secuser> ImportFile (MultipArtFile MFile, String RootPath) {รายการ <Secuser> secUserList = arrayList ใหม่ <Secuser> (); String filename = mfile.getoriginalfilename (); สตริงคำต่อท้าย = filename.substring (filename.lastindexof (".") +, filename.length ()); String ym = ใหม่ simpledateFormat ("yyyy-mm") รูปแบบ (วันที่ใหม่ ()); String filePath = "UploadFile/" + YM + ชื่อไฟล์; ลอง {file file = ไฟล์ใหม่ (rootpath + filePath); if (file.exists ()) {file.delete (); file.mkdirs (); } else {file.mkdirs (); } mfile.transferto (ไฟล์); if ("XLS" .Equals (คำต่อท้าย) || "XLS" .Equals (คำต่อท้าย)) {secUserList = importXLS (ไฟล์); ieportdao.importfile (secuserlist); } อื่นถ้า ("xlsx" .equals (คำต่อท้าย) || "xlsx" .equals (คำต่อท้าย)) {secuserlist = importxlsx (ไฟล์); ieportdao.importfile (secuserlist); }} catch (exception e) {e.printstacktrace (); } return secuserlist; } รายการส่วนตัว <Secuser> importXLS (ไฟล์ไฟล์) {รายการ <Secuser> secUserList = new ArrayList <Secuser> (); InputStream คือ = null; HSSFWORKBOOK HORKBOOK = NULL; ลอง {IS = ใหม่ FileInputStream (ไฟล์); HORKBOOK = HSSFWORKBOOK ใหม่ (IS); hssfsheet hsheet = hworkbook.getSheetat (); if (null! = hsheet) {สำหรับ (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 (); } ในที่สุด {ถ้า (null! = IS) {ลอง {is.close (); } catch (exception e) {e.printstacktrace (); }} if (null! = hworkbook) {ลอง {hworkbook.close (); } catch (exception e) {e.printstacktrace (); }}} ส่งคืน secuserlist; } รายการส่วนตัว <Secuser> importxlsx (ไฟล์ไฟล์) {รายการ <Secuser> secUserList = new ArrayList <Secuser> (); InputStream คือ = null; xssfworkbook xworkbook = null; ลอง {IS = ใหม่ FileInputStream (ไฟล์); xworkbook = ใหม่ XSSFWORKBOOK (IS); XSSFSHEET XSheet = XWorkBook.getSheetat (); if (null! = xsheet) {สำหรับ (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 (); } ในที่สุด {ถ้า (null! = IS) {ลอง {is.close (); } catch (exception e) {e.printstacktrace (); }} if (null! = xworkbook) {ลอง {xworkbook.close (); } catch (exception e) {e.printstacktrace (); }}} ส่งคืน secuserlist; } โมฆะสาธารณะ ExportFile (การตอบสนอง httpservletResponse) {simpledateFormat df = ใหม่ simpledateFormat ("yyyymmdd"); OutputStream OS = NULL; xssfworkbook xworkbook = null; ลอง {String filename = "ผู้ใช้" + df.format (วันที่ใหม่ ()) + ".xlsx"; OS = response.getOutputStream (); Response.reset (); Response.SetheAder ("เนื้อหา-การจัดสรร", "สิ่งที่แนบมา; ชื่อไฟล์ =" + urlencoder.encode (ชื่อไฟล์, "UTF-")); Response.SetContentType ("แอปพลิเคชัน/octet-streem"); xworkbook = ใหม่ xssfworkbook (); XSSFSHEET XSheet = XWORKBOOK.CREATESHEET ("USERLIST"); // ชุดส่วนหัวแผ่น Setsheetheader (Xworkbook, XSheet); // ตั้งค่าหน้าแผ่นเนื้อหา SetSheetContent (XWORKBOOK, XSheet); xworkbook.write (OS); } catch (exception e) {e.printstacktrace (); } ในที่สุด {ถ้า (null! = os) {ลอง {os.close (); } catch (exception e) {e.printstacktrace (); }} if (null! = xworkbook) {ลอง {xworkbook.close (); } catch (exception e) {e.printstacktrace (); }}}}} / ** * ชุดส่วนหัวแผ่น * @param xworkbook * @param xsheet * / โมฆะส่วนตัว 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); // ตั้งค่าตัวอักษร FONT HeaderFont = XWorkBook.CreateFont (); headerfont.setfontheightinpoints ((สั้น)); headerfont.setboldweight (xssffont.boldweight_bold); headerFont.SetFontName ("安体"); cs.setfont (headerfont); Cs.SetWrapText (จริง); // เป็นไปได้ไหมที่จะห่อเส้น xssfrow xrow = xsheet.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 ("รหัสผ่าน"); } / ** * ตั้งค่าเนื้อหาหน้าแผ่น * @param xworkbook * @param xsheet * / โมฆะส่วนตัว setsheetContent (XSSFWORKBOOK XWORKBOOK, XSSFSHEET XSheet) {รายการ <Secuser> CellStyle CS = XWORKBOOK.CreateCellStyle (); cs.setWrapText (จริง); if (null! = secuserlist && secuserlist.size ()>) {สำหรับ (int i =; i <secuserlist.size (); i ++) {xssfrow xrow = xsheet.createrow (i+); secuser secuser = secuserlist.get (i); สำหรับ (int j =; j <; j ++) {xssfcell xcell = xrow.createCell (j); xcell.setcellstyle (CS); สวิตช์ (j) {กรณี: xcell.setCellValue (secuser.getUserId ()); หยุดพัก; กรณี: xcell.setCellValue (secuser.getUserName ()); หยุดพัก; กรณี: xcell.setCellValue (secuser.getUserPassword ()); หยุดพัก; ค่าเริ่มต้น: break; -Dao:
แพ็คเกจ com.dao; นำเข้า java.sql.resultset; นำเข้า java.sql.sqlexception; นำเข้า java.util.arraylist; นำเข้า java.util.list; นำเข้า Javax.annotation.Resource; นำเข้า org.springframework.stereotype.repository; นำเข้า com.domain.secuser; นำเข้า org.springframework.jdbc.core.jdbctemplate; นำเข้า org.springframework.jdbc.core.rowmapper; @Repository คลาสสาธารณะ ieportdao {@Resource ส่วนตัว JDBCTEMPLATE JDBCTEMPLATE; Private Rowmapper <Secuser> SurowMapper = NULL; ส่วนตัว ieportdao () {surowmapper = ใหม่ rowmapper <secuser> () {@Override สาธารณะ secuser สาธารณะ maprow (ผลลัพธ์ RS, ดัชนี int) โยน sqlexception {secuser secuser = new Secuser (); secuser.setUserId (rs.getString ("user_id")); secuser.setUserName (rs.getString ("user_name")); secuser.setUserPassword (rs.getString ("user_password")); คืน Secuser; - } โมฆะสาธารณะนำเข้า (รายการ <secuser> secuserlist) {ลอง {string sql = "แทรกลงในค่า sec_user (uuid (),?,?)"; รายการ <object []> paramslist = new ArrayList <Object []> (); สำหรับ (int i =; i <secuserlist.size (); i ++) {secuser secuser = secuserlist.get (i); Object [] params = วัตถุใหม่ [] {secuser.getUserName (), secuser.getUserPassword ()}; paramslist.add (params); } jdbctemplate.batchupdate (sql, paramslist); } catch (exception e) {e.printstacktrace (); }} รายการสาธารณะ <Secuser> getSecuserList () {list <Secuser> sulist = new ArrayList <Secuser> (); StringBuffer sb = new StringBuffer (); sb.append ("เลือก su.user_id, su.user_name, su.user_password จาก sec_user su"); ลอง {sulist = jdbctemplate.query (sb.toString (), surowmapper); } catch (exception e) {e.printstacktrace (); } return sulist; -โดเมน:
แพ็คเกจ com.domain; Secuser คลาสสาธารณะ {String userId; // id id id String ชื่อผู้ใช้ชื่อ; // username string userpassword; // รหัสผ่านสาธารณะสตริงสาธารณะ getUserId () {return userId; } โมฆะสาธารณะ setUserId (String userId) {this.userId = userId; } สตริงสาธารณะ getUserPassword () {return userPassword; } โมฆะสาธารณะ setUserPassword (String userPassword) {this.userPassword = userPassword; } สตริงสาธารณะ getUserName () {ส่งคืนชื่อผู้ใช้; } โมฆะสาธารณะ setUserName (ชื่อผู้ใช้สตริง) {this.userName = ชื่อผู้ใช้; -4. ไฟล์กำหนดค่า:
<? xml version = "." การเข้ารหัส = "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/javaee/web-app__.sd <Shade-Name> SpringspringMvcpoi </display-name> <welcome-file-list> <welcome-file> ieeport.jsp </welcome-file> </welcome-file-list> <!-ระบุชื่อและตำแหน่งของไฟล์การกำหนดค่าสปริง- classpath: dataSource-context.xml </param-value> </context-param> <!-กำหนดค่าผู้ฟัง-> <ผู้ฟัง> <Sistener-class> org.springframework.web.context.contextloaderListener </listener-class> <servlet-name> dispatcherservlet </servlet-name> <servlet-class> org.springframework.web.servlet.dispatcherservlet </servlet-class> <! <param-value> classpath: Spring-Mvc.xml </param-value> </init-param> </servlet> <servlet-mapping> <servlet-name> dispatcherservlet </servlet-name> <url-pattern>*. go </url-pattern> <tilter-name> ตัวละคร actaryencodingfilter </filter-name> <filter-class> org.springframework.web.filter.characterencodingFilter </filter-class> <init-param> <param-name> การเข้ารหัส </param-name> <tilter-name> ตัวละคร actialencodingfilter </filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </eb-app>
<? xml version = "." การเข้ารหัส = "utf-"?> <ถั่ว 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.schema/aop xmlns: mvc = "http://www.springframework.org/schema/mvc" xmlns: util = "http://www.springframework.org/schema/util http://www.springframework.org/schema/beans/spring-beans-..xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-..xsd http://ww.springframework http://www.springframework.org/schema/aop/spring-aop-..xsd "> <!-กำหนดค่าแพ็คเกจการสแกนอัตโนมัติ-> <บริบท: Component-Scan base-package =" com.controller "> </บริบท: Component-Scan> <! value = "/web-inf/views/"> </property> <property name = "suffix" value = ". jsp"> </porement> </ebean> <!-สนับสนุนการอัปโหลดไฟล์-> <bean id = "MultipartResolver"/> </epeans>
<? xml version = "." การเข้ารหัส = "utf-"?> <ถั่ว 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/context http://www.springframework.org/schema/Contex
<? xml version = "." การเข้ารหัส = "utf-"?> <ถั่ว 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/context http://www.springframework.org/schema/context/spring-context.xsd "> <! <bean id = "dataSource" destroy-method = "close"> <property name = "user" value = "$ {jdbc.user}"> </คุณสมบัติ> <property name = "รหัสผ่าน" value = "$ {jdbc.password}"> </property> <property name = "driverclass value = "$ {jdbc.jdbcurl}"> </property> <!-เมื่อการเชื่อมต่อในกลุ่มการเชื่อมต่อถูกใช้งานจำนวนการเชื่อมต่อใหม่ที่สร้างขึ้นในครั้งเดียวโดย cp-> <property name = "AcquireIncrement" value = "> </property> <!-จำนวนการเชื่อมต่อที่สร้างขึ้นระหว่างการเริ่มต้น value = ""> </property> <property name = "maxPoolSize" value = ""> </คุณสมบัติ> <property name = "minpoolsize" value = ""> </property> <property name = "maxConnectionage" value = ""> </property> <property name = "testConnectionOnCheckout" value = "false"> </property> <property name = "testConnectionOnCheckin" value = "false"> </property> <!-ตรวจสอบการเชื่อมต่อที่ไม่ได้ใช้งานในพูลการเชื่อมต่อทุกวินาที-> <property name = "IdleConNectionTestPeriod" value = " name = "acquireeretryDelay" value = ""> </คุณสมบัติ> <property name = "preferredTestQuery" value = "เลือกจาก dual"> </property> </ebean> <!-กำหนดค่าเทมเพลต JDBC jdbctemplate-> <bean id = "JdBctemplate"jdbc.driverclass = com.mysql.jdbc.driver jdbc.jdbcurl = jdbc: mysql: // localhost:/mydb jdbc.user = myuser jdbc.password = myuser
5. โครงสร้างไดเรกทอรี:
6. การสาธิตผลลัพธ์
นำเข้า:
ส่งออก:
PS:
1. สามเณรนี้เนื่องจากเธอยังไม่ทราบวิธีเพิ่มไฟล์แนบเธอโพสต์รหัสทั้งหมดและเพิ่มโครงสร้างไดเรกทอรี เธอจะได้เรียนรู้วิธีเพิ่มไฟล์แนบในอนาคตจากนั้นแก้ไข
ข้างต้นเป็นเนื้อหาทั้งหมดของบทความนี้ ฉันหวังว่ามันจะเป็นประโยชน์ต่อการเรียนรู้ของทุกคนและฉันหวังว่าทุกคนจะสนับสนุน wulin.com มากขึ้น