1. 개념 소개
Apachepoi는 Apache Software Foundation의 오픈 소스 라이브러리입니다. POI는 API에서 Java 프로그램을 제공하여 Microsoft Office Format Archives를 읽고 작성합니다.
2. 기능 관련 코드
1. 환경 설명 : JDK1.7+TOMCAT7+스프링
2. 구성 파일 구성
POM 파일에 필요한 POI 종속성을 추가하십시오
<!-POI 지원-> <pectionency> <groupId> org.apache.poi </groupid> <artifactid> poi </artifactid> <version> version> 3.13 </version> </fectionency> <pectionency> <groupId> org.apache.poi </groupid> <artifactid> poi-ooxml> <버전 3.13> 3.13> 3.13> 3.13> 3.13>.
spring-mvc.xml 구성 파일 업로드
<bean id = "multipartresolver"> <!-기본 인코딩-> <property name = "defaultencoding"value = "utf-8" /> <!-최대 파일 크기 값-> <속성 이름 = "maxUploadSize"value = "10485760000" /> <!-메모리의 최대 값-> < /ban "
3. 관련 도구 수업 및 코드 쓰기
Excel Parsing Tool Class (importexcelutil.java)
package com.jointem.hrm.utils; import org.apache.poi.hssf.usermodel.hssfworkbook; import org.apache.s.usermodel.cell; import org.apache.poi.ss.usermodel.row; import org.apache.poi.ss.s.sermodel.sheet; org.apache.poi.ss.usermodel.workbook; import org.apache.poi.util.cellrangeaddress; import org.apache.poi.xssf.usermodel.xssfworkbook; import java.io.ioexception; import java.io.inputstream; import java.text.decimalformat; java.text.simpledateformat; import java.util.arraylist; import java.util.list;/*** Jenking이 2017/9/8에 생성했습니다. */public class importexcelutil {개인 최종 정적 문자열 Excel2003l = ". xls"; // 2003- Excel 개인 최종 정적 문자열 Excel2007U = ". XLSX"; // 2007+ Excel의 버전/** * 설명 : IO 스트림에서 데이터를 가져 와서 목록 <목록 <객체 >> 객체 * @param in, filename * @return * @throws ioexception */public list <object >> getBanklistByExcel (InputStream in, String filename) 예외 {objebs <list >> null; // Excel 통합 문서 작성 작업 = this.getWorkbook (in, filename); if (null == work) {새 예외 던지기 ( "Excel 워크 시트를 비어!"); } 시트 시트 = null; 행으로 = null; 세포 세포 = null; list = new ArrayList <list <객체 >> (); // 고음성 (int i = 0; i <work.getNumberOfSheets (); i ++) {sheet = work.getSheetat (i); if (sheet == null) {계속;} // tranquility 현재 시트 System.out.println (sheet.getLastrownum ())의 모든 행; for (int j = sheet.getfirstrownum (); j <= sheet.getlastrownum () -11; for (int y = row.getFirstCellNum (); y <row.getLastCellNum (); y ++) {cell = row.getCell (y); if (this.ismergedergion (시트, j, y)) {li.add (this.getmerged Regionvalue (sheet, j, y)); } else {li.add (this.getCellValue (Cell)); }} list.add (li); }} work.close (); 반환 목록; } / ** * 설명 : 파일 접미사에 따르면, 적응 적으로 업로드 된 파일의 버전 * @param instr, filename * @Throws Exception * / public workbook getWorkbook (inputStream Inst, String Filename) 예외 {Workbook wb = null; String filetype = filename.substring (filename.lastindexof ( ".")); if (excel2003l.equals (filetype)) {wb = new Hssfworkbook (Inst); // 2003-} else if (Excel2007U.equals (filetype)) {wb = new xssfworkbook (instr); // 2007+} else {Throw New Exception ( "구문 분석 파일 형식이 잘못되었습니다!"); } return wb; } / ** * 설명 : 테이블의 값을 형성 * @param cell * @return * / public object getCellValue (셀 셀) {object value = null; Decimalformat df = 새로운 십진형 ( "0"); // 형식 번호 문자열 문자 simpledateformat sdf = new SimpledateFormat ( "yyy-mm-dd"); // 날짜 형식 DECIMALFORMAT DF2 = NEW DECIMALFORMAT ( "0"); // 형식 번호 switch (cell.getCellType ()) {case cell.cell_type_string : value = cell.getRichstringCellValue (). getString (); 부서지다; case cell.cell_type_numeric : if ( "general".equals (cell.getCellStyle (). getDataFormatString ())) {value = df.format (cell.getNumericCellValue ()); } else if ( "m/d/yy".equals (cell.getCellStyle (). getDataFormatString ())) {value = sdf.format (cell.getDateCellValue ()); } else {value = df2.format (cell.getNumericCellValue ()); } 부서지다; case cell.cell_type_boolean : value = cell.getBooleanCellValue (); 부서지다; case cell.cell_type_blank : value = ""; 부서지다; 기본값 : 브레이크; } 반환 값; } / ** * 병합 된 셀의 내용을 가져옵니다. for (int i = 0; i <sheremergecount; i ++) {cellrangeaddress ca = sheet.getmerged Region (i); int firstColumn = ca.getFirstColumn (); int lastcolumn = ca.getLastColumn (); int firstrow = ca.getfirstrow (); int lastrow = ca.getLastrow (); if (row> = firstrow && row <= lastrow) {if (column> = firstColumn && column <= lastColumn) {row frow = sheet.getrow (firstrow); cell fcell = frow.getCell (FirstColumn); getCellValue (fcell)를 반환합니다. }} return null; } / ** * 병합 된 셀 * @param sheet * @param row * @param 열 * @return * / public boolean ismerged Region (시트 시트, int 행, int 열) {int shetmergecount = sheet.getnummergedregions (); for (int i = 0; i <sheremergecount; i ++) {cellrangeaddress 범위 = 시트. int firstColumn = Range.GetFirstColumn (); int lastColumn = Range.GetLastColumn (); int firstrow = range.getFirstrow (); int lastrow = range.getLastrow (); if (row> = firstrow && row <= lastrow) {if (column> = firstColumn && column <= lastColumn) {return true; }}} 거짓을 반환합니다. }} 요청 컨트롤러 (프로세스 페이지 Excel 가져 오기 요청)
패키지 com.poiexcel.control; import java.io.inputstream; import java.io.printwriter; Java.util.list 가져 오기; import javax.servlet.http.httpservletrequest; import javax.servlet.http.httpservletresponse; org.springframework.stereotyp.controller import; org.springframework.web.bind.annotation.requestmapping; org.springframework.web.bind.annotation.requestmethod; org.springframework.web.bind.annotation.responsebody; org.springframework.web.multipart.multipartfile; org.springframework.web.multipart.multiparthttpservletrequest; com.poiexcel.util.importexcelutil 가져 오기; com.poiexcel.vo.infovo import; @controller @requestmapping ( "/uploadexcel/ *")) 공개 클래스 UploadexcelControl {/** * 설명 : 기존 양식 제출 * @param request * @throws Exception */@requestmapping (value = "upload.do", method = {requestmethod.post}))를 통해 Excel 파일 가져 오기 Uploadexcel (httpservletrequest request) 예외 {multiparthttpservletrequest multipartrequest = (multiparthttpservletrequest) request; inputStream in = null; List <list <object>> listob = null; multipartfile 파일 = multipartrequest.getFile ( "upfile"); if (file.isempty ()) {Throw New Exception ( "파일이 존재하지 않습니다!"); } in = file.getInputStream (); listob = new importexcelutil (). getBankListByExcel (in, file.getoriginalFilename ()); 넣다(); // 데이터를 데이터베이스에 저장하기 위해 해당 서비스 방법을 호출 할 수 있습니다. 이제 데이터 만 출력됩니다 (int i = 0; i <listob.size (); i ++) {list <botor> lo = listob.get (i); infovo vo = 새로운 infovo (); Vo.SetCode (String.Valueof (lo.get (0)); vo.setName (String.Valueof (lo.get (1)); Vo.SetDate (String.Valueof (lo.get (2)); vo.setmoney (String.valueof (lo.get (3)); System.out.println ( "인쇄 정보-> 기관 :"+vo.getCode ()+"이름 :"+vo.getName ()+"time :"+vo.getDate ()+"asset :"+vo.getMoney ()); } return "result"; } 프론트 엔드 코드
프런트 엔드는 파일 업로드 컴포넌트 파일 파일 파일 파일을 사용하여 fileInput.css, fileInput.js, Zh.js, bootstrap.css, bootstrap.js, jquery.min.js를 소개해야합니다.
<body> <h4> 출석 정보 입력 </h4> <form 메소드 = "post"enctype = "multipart/form-data"id = "form1"action = "$ {pagecontext.request.contextpath}/envernance/uploadexcel"> <input id = "file-zh"name = "upfile" "form"> form> </body> </body>> $ ( '##file-zh'). fileInput ({language : 'zh', uploadurl : '$ {pagecontext.request.contextpath}/enderance/uploadexcel', allendfileextensions : [ 'xls', 'xlsx'}); </script> VO 객체, Excel 데이터의 해당 객체를 저장하십시오
패키지 com.poiexcel.vo; // 엑셀의 각 행을 객체로 변환 공개 클래스 infovo {private String code; 개인 문자열 이름; 개인 문자열 날짜; 개인 문자열 돈; public String getCode () {return code; } public void setCode (문자열 코드) {this.code = code; } public String getName () {return name; } public void setName (문자열 이름) {this.name = 이름; } public String getDate () {return date; } public void setDate (문자열 날짜) {this.date = date; } public String getMoney () {return money; } public void setMoney (String Money) {this.money = Money; }}3. 효과 디스플레이
1. 페이지 디스플레이
2. 백엔드 정보를 인쇄합니다
4. 요약
이 예제는 콘솔에서 가져온 데이터 만 출력하며 지속되지 않습니다. 지속하려면 주석 위치에서 서비스 계층에 전화하십시오.
위는이 기사의 모든 내용입니다. 모든 사람의 학습에 도움이되기를 바랍니다. 모든 사람이 wulin.com을 더 지원하기를 바랍니다.