이 기사는 참조를 위해 Excel 테이블 데이터의 배치 가져 오기를 Java로 공유합니다. 특정 내용은 다음과 같습니다. import java.awt.color; import java.io.bytearrayinputstream; import java.io.BytearRayoutputStream; import java.io.file; import java.io.fileInputStream; import java.io.inputstream; import java.lang.reflect.field; import java.text.dateformat; import java.text.decimalformat; import java.text.simpledateformat; java.util.*; import javax.swing.text.attributeset; import javax.swing.text.element; import javax.swing.text.html.css; import javax.swing.text.html.htmldocument; import javax.swing.text.html.htmleditorkit; cn.vrview.dev.common.exception.businessException 가져 오기; import org.apache.commons.lang3.stringutils; import org.apache.logging.log4j.logmanager; import org.apache.logging.log4j.logger; import org.apache.poi.hssf.usermodel.*; import org.apache.poi.hssf.util.hssfcolor; import org.apache.poi.ss.usermodel.*; import org.apache.poi.ss.util.cellrangeaddress; import org.apache.poi.xssf.usermodel.xssfcolor; import org.apache.poi.xssf.usermodel.xssffont; import org.apache.poi.xssf.usermodel.xssfworkbook; import org.springframework.web.util.htmlutils; cn.vrview.dev.common.util.stringutil import; 공개 클래스 ExcelTools { / ** log* / private static logger log = logmanager.getLogger (); /** * Export Excel * <p> * 사용법 : <br> * <crod> list <map <string, object >> 객체 >> datalist = new arraylist <string <string, object >> (); <br> * is = exceltools.exportxls (새 문자열 [] { "createTime : date", "name :"sex ","}); * </ code> * * @Param Collect * 내보내기 * @Param 헤더 * 내보내기 할 수 있습니다 * @return inputStream 리턴 파일 스트림 */ public static inputStream ExportXls (collection <map <string, object >> string [] header) {bytearRayoutputStream out = new ByTearRayoutStream (); hssfworkbook book = 새로운 hssfworkbook (); {// 시트 추가 hssfsheet sheet = book.createsheet ( "sheet1"); // 내보낼 열 이름 세트를 정의하십시오. // 셀 배경 색상 설정 hssfcellstyle cellstyle = book.createcellstyle (); cellstyle.setfillpattern (hssfcellstyle.solid_foreground); cellstyle.setfillforegroundColor (new hssfcolor.yellow (). getIndex ()); // 헤더 생성 hssfrow row = sheet.createrow (0); hssfcell cell = row.createcell (0); Cell.setCellStyle (CellStyle); cell.setCellValue ( "시퀀스"); // 열 번호는 1 Int n = 1에서 시작합니다. // (문자열 str : 헤더) {string [] arr = str.split ( ":"); columns.add (n + "," + arr [0]); // 필드 이름을 내보내고 열 숫자 n cell = row.createcell (n)에 바인딩 할 필드 이름을 추가합니다. Cell.setCellStyle (CellStyle); cell.setCellValue (ARR [1]); n ++; } // 1, 0부터 시작하는 데이터 행을 생성합니다. 0은 헤더 int i = 1입니다. // (map <string, object> map : collect) {hssfrow datarow = sheet.createrow (i); // 시퀀스 번호 Datarow.CreateCell (0) .SetCellValue (i)를 생성합니다. // (문자열 열 : 열) {// 쉼표를 사용하여 필드 이름을 얻으려면 [0]은 헤더 헤더에 해당하는 열 번호입니다. 문자열 columnname = column.split ( ",") [1]; // 시퀀스 번호 열 셀을 생성 셀 = Datarow.createCell (integer.parseint (column.split ( ",") [0]); 문자열 값 = ""; 값 = map.get (columnName) + ""; // ""if ( "null".Equals (value)) {value = ""로 변환; } richtextstring richtextstring = processhtml (책, 값); cell.getCellStyle (). setWrapText (false); Cell.setCellValue (RichtexTString); } i ++; } book.write (out); out.close (); } catch (예외 e) {e.printstacktrace (); } 새로운 BYTEARRAYINPUTSTREAM을 반환합니다 (out.TobyTeArray ()); } /** * Excel 파일 데이터 가져 오기 <br> * usage : <br> * sheetInfo sheetInfo = new ExcelTools (). new SheetInfo (); <br> * sheetInfo.setRowTitle (0); List <string> sheets = new ArrayList <String> (); <br> * String SheetName = "Sheet1"; sheets.add (sheetname); <br> * sheetinfo.setsheetnames (Sheets); <br> * sheetInfo.setColumnsMapping (new String [] { "prodName : product name", * "prodSpec : specification", "collectPrice :" + {@link regexpenum} * regexpenum.notempty_isnumber : "unitation :"collectmarket : * "prodlevel :"); <br> * map <string, list> data = exceltools.getexcel (새 파일 (path), sheetinfo); * * @param * * @param sheetinfo * 초기화 정보 * @return map {sheet1 : list} * @throws 예외 * 예외 */ @suppresswarnings ( "rawtypes") public static map getExcel (파일 f, string exceltype) 예외 {return getextream (f), excelypo); } @SuppressWarnings ({ "rawtypes", "unchecked"}) public static map getExcel (inputStream in, sheetInfo sheetInfo, String ExcelType) 예외 {map <string, string> columnsmap = new Hashmap <String, String> (); // 열 검증 표현식 맵 목록 <string> errmsg = new ArrayList <string> (); int errnum = 0; // 총 오류 수 int errlimit = 10; // 지정된 규칙에 따라 읽는 모든 내용을 저장하는 데 사용되는 오류 숫자 숫자/ ** 제한*/ map xcelinfo = new hashmap (); 통합 문서 책 = null; try {if (exceltype.equals ( "xls")) {book = new hssfworkbook (in); // 새로운 BusinessException을 던지십시오 ( "Excel 버전은 너무 낮습니다. 버전 2007 이상 (Extension : XLSX)을 사용하십시오. } else {book = new xssfworkbook (in); }} catch (outofMemoryError e) {throw new runtimeexception ( "현재 Excel 파일이 너무 큽니다. 형식 및 와이어 프레임이있는 행 및 열 데이터를 포함하여 각 시트 테이블에 잘못된 빈 데이터가 있는지 확인하십시오. } // CheckTitle (Book, SheetInfo); // 워크 시트 수를 가져옵니다 int sheetnum = sheetInfo.getSheetNames (). size (); // 모든 워크 시트를 루프하고 내부의 데이터를 읽습니다 (int sheetIndex = 0; sheetIndex <sheetnum; sheetindex ++) {// 현재 워크 시트 객체 string sheetname = htmlutils.htmlunescape (sheetinfo.getsheetnames (). get (sheetindex)); map <string, string> validAtemap = new Hashmap <String, String> (); for (string mapstr : sheateinfo.getColumnsMapping (). get (sheetName)) {string [] arr = mapstr.split ( ":"); columnsmap.put (arr [1], arr [0]); if (arr.length == 3) {// 확인 표현식이 비어 있지 않으면 맵에 validAmap.put (ARR [1], ARR [2])에 추가하십시오. }} 시트 시트 = book.getSheet (SETERNAME); if (null == sheet) {wrach new runtimeexception (String.format ( "테이블을 얻지 못하면 시트"%s "가 excel에 존재하는지 여부를 확인하십시오", Sheetname); } // 데이터 컨텐츠를 워크 시트 목록에 저장하는 데 사용되었습니다. SheetList = New ArrayList (); // 현재 테이블에서 행 수를 가져옵니다 int rows = sheet.getLastrownum (); // 현재 테이블에서 열 수를 가져옵니다. int columns = sheet.getrow (sheetInfo.getRowTitle ()). getLastCellNum (); if (rows <= sheetInfo.getRowTitle ()) {// 현재 테이블에 필요한 데이터가없는 경우 다음 루프를 계속하십시오. } // 현재 워크 시트 제목 컨텐츠 목록을 가져옵니다. <string> titlelist = new Arraylist <string> (); // 각 행의 모든 셀을 루프하고 셀 로우의 값을 읽습니다. titlerow = sheet.getrow (sheetInfo.getRowTitle ()); for (int jj = 0; jj <컬럼; if (celltitle! = null) {int row = celltitle.getRowIndex (); int column = celltitle.getColumnIndex (); if (ismerged Region (시트, 행, 열)) {titlelist.add (getmerged Regionvalue (시트, 행, 열)); } else {titlelist.add (getCellValue (CellTitle)); }} else {throw new runtimeexception ( "테이블 헤더 읽기 오류, 현재"th " + (sheetInfo.getRowTitle () + 1) +"row <br/> 테이블 헤더의 내용은 다음과 같습니다. " + titlerow +", 예외가 있으면 헤더 형식을 삭제하고 헤더를 삭제할 수 있습니다! "). system.out.println (titlelist); (stringutils.deletewhitespace (t) .equalsignorecase (colarr [1]) {include; include; for (int i = sheateinfo.getrowtitle () + 1; i <= rows; i ++) {new hashmap (); j ++; columnsmap.keyset () {stringUtils.deleteWhitespace (columntitle) 색상 if ( "xls")) {hssfcolor color = (hssfcolor) cellstyle.getfillforegroundcolorcolor (); XSSFCOLOR = (XSSFCOLOR) 셀 스타일 (mergrow> 0 &&! stringUtil.isempty (value)) {String Rowspan = ""; 1); 셀 columnsmap.get (columntitle) eum.getText (! value.trim ()는 일치하지 않습니다! // getMerged RegionValue (sheet, row, column); (Errmsg.size ()> 0) {if (errnum> errlimit) {errmsg.add ( "Total" + errnum + "항목이 너무 많습니다. 템플릿 데이터가 올바른지 확인하십시오. // (true) 새로운 runtimeexception ( "테스트"excelinfo <hashmap <string, string (sheetinfo sheetinfo)은 {string, string> columnsmap = newhmap <string, string> (); string> (); new arraylist <string> (); // int errlimit = 10; ARR [0]; arr.length == 3) {// validAmap.put에 맵에 추가하십시오. checktitle (book, sheetinfo); Worksheet // SETERLIST = NEW ARRAYLIST (); } int columns = titlerow.getLastCellNum (); columns! = sheateinfo.getColumnsMapping ( "). 다음 번에 새로운 BusinessException을 던지기 위해 (파일 형식은 템플릿을 재 선출하거나 다운로드하십시오.} // 각 행에있는 모든 셀을 루프하고 셀의 값을 읽습니다. titlelist.add (titlerow.getCell (jj) .getStringCellValue ()); (! titlelist.contains (s.split ( ":"))) {// errmsg.add ( " ' + sheet.getsheetname () +" + s // + "'열이 존재하지 않습니다!" (int i = getrowtitle ()+1; i <= rows; i ++) {new hashmap (); ( ". Columntitle) {셀 셀 value = getCellValue (셀); valideMap.get (columntitle)) {// 정규 표현식 regexpenum eum = regexpenum.get (columntitle); (value.matches (validatereg)) {rowmap.put (columnmapping, value) {errnum <= errlimit) {errmsg.add ( "th" + i + "line : [" + columntitle + ". "</br>/n"} else {rowmaping, value}} excelinfo.put {// errmsg.add (가져온 데이터 템플릿은 너무 많은 형식의 오류입니다. 테이블 초기화 정보** @author : ji le* @date : 2013-12-2 1:43:04 pm* @since : 1.0*/ public class sheetInfo {/ ** 제목이 위치한 줄은 1*/ private int rowtitle = 1에 대한 1*/ private rowtitle = 1; / ** 읽어야하는 시트의 이름* / public list <string> sheetnames = new ArrayList <string> (); this.sheetnames = regetinfo (}} {// SETERNAME가 정의되지 않으면 (null == SETERNAMES.size) rowtitle) {rowtitle = rowtitle; setSheetNames (list <string> sheetnames) {this.sheetnames = sheetnames}} / **** @author : jile* @date : 2013-12-2 1:43:24 pm* @since : 1.0* / public enum regexpenum { / ** +nopment (? /**는 숫자가되어야합니다 ( "// d*",/** 숫자*/notempty_isnumber ( "// d+"); regexpenum (문자열 텍스트, 문자열 값) {this.text = text. wb, richtextring rt = null; StringBuffer (int lines = 0, lastpos = -1) {// if (line> 0) {// ELIDX ++) {최종 요소 조각 = line.getElement (ELIDX); doc.getText (), prast.getEndOffset () - subText.equals ( "/n"); wb.getCreationHelper (); getElementCount () {최종 요소 Fragment = getFontfromfragment (rt.applyfont); // e.printstacktrace ()} rt}; fragment.getattributes (); F. setAccessible (true) f.get (as.getAttrib) {((xssffont) font). (HSSFWorkbook) .getCustOmpalett (); c.getress (), c.getgreen () (Bold " STERMERGERCOUNT; I ++) {// 특정 셀 레인지 드레드 CA = Getmerged Region (I); // 셀이 합병 된 셀의 범위 내에 있는지 확인합니다. @Param Column */ public static string getmerged Regionvalue (시트, int row, int column) {int i = 0; i <shermergecount; i ++) {cellrangeaddress ca.getlastcolumn () int firstrow (); getCellValue (fcell)}}}}; SheatergeCount; intrangeadress range = int firstcolumn (int firstcolumn). > = Column <= LastColumn) {return}} retry}} * 셀이 포함되어 있는지 * @param sheet * /@suppresswarnings ( "Unused") * @param firstrow * 시작 행 * @param lastrow * end row * @param firstcol * start column * @param lastcol * end column */ @suppresswarnings ( "Unused") private void mergeregion (시트 시트, int firstrow, int lastrow, int firstcol, int lastcol) {New Pheater, lastrow, lastrow, bastrow, bastrow, bastrow, lastorged. lastcol);} / ** * 셀 값을 얻습니다 * @param cell * @return * / public static string getCellValue (셀 == null) return ""; cell.cell_type_boolean) {return string.valueof (cell.getBooleanCellValue ()); (hssfdateutil.iscelldateformatted (cell)) {// SimpledateFormat ( "yyyy-mm-dd"); (셀. getCellStyle (). getDataFormat () == 31) {// COSTOM DATE 형식 : yy 년 MM MONTH DD 날짜 (ID의 값은 3 1) org.apache.ss.usermodel.getjavadate (value); string.valueof (value)}} public static string filterstr (str.replace ((char) 160)). System.out.println (convertrgbtohex (hssfcolor.yellow.triplet); 정적 인 ConvertrgbtoHex (int r = rgb [1], BFSTRING, BFSTRING, BSSTRING; rfstring = else (red ==) rfstring = "rfstring ="d "; rsstring = else (rred == 12) rsstring = "rred = 1 14"라는 경우; rfstring + rsstring = gfstring = gfstring = "geen == 12) gfstring = else gfstring "E"; "BFSTRING (Blue == 14) else (blue = 15); BSSTRING은 (rblue == 14) else (rblue = 15); 결과; } } From.jsp 페이지를 다시보십시오
<body> <div> <form id = "mainform"action = "$ {ctx}/bom/ciscaseacect/$ {action}"method = "post"enctype = "multipart/form-data"> <input type = "file"name = "file"/<a href = "$ {ctx}/case import. 템플릿 </a> </form> </div> <script type = "text/javaScript"> $ (function () {$ ( '#mainform'). form ({onsubmit : function () {var isvalid = $ (this) .form ( 'validate'); return isvalid; // return retlicate form submission}, data (data) {data) < })); </script> </body>메인 인터페이스 JSP
다음과 같이 코드를 복사하십시오. <a href = "javaScript (0)"rel = "external nofollow"plain = "true"iconcls = "icon-standard-application-go"onclick = "importAction ()"> import </a>
// import function importAction () {d = $ ( "#dlg"). 대화 상자 ({제목 : 'case import', width : 500, 높이 : 500, href : '$ {ctx}/bom/ciscaseaction/importaction/', maximizable : true, modal : true, buttons : [texm : 'handler'() }}, {text : 'cancel', handler : function () {d.panel ( 'close')}; }페이지를 클릭하는 효과는 가져 오기를 클릭하면 From.jsp 페이지로 이동한다는 것입니다.
컨트롤러 계층을 다시보십시오
/ *** 가져 오기 페이지*/ @RequestMapping (value = "importAction", method = requestMethod.get) public String importform (모델 모델) {model.addattribute ( "action", "import"); "System/CiscaseacectionimoPortform"을 반환합니다. } / *** import* / @requestmapping (value = "import", method = requestmethod.post) @ResponseBody public string importform (@requestParam ( "file") multipartFile multipartFile, Model Model) 예외 {ciscaseactionservice.upload (multipartfile); "성공"을 반환합니다. } 서비스 계층
/ *** import case*/ @suppresswarnings ({ "rawtypes", "unchecked"}) public void upload (multipartfile multipartfile) 예외 {inputStream inputStream = multipartFile.getInputStream (); Exceltools Exceltools = New Exceltools (); Exceltools.sheetInfo sheetInfo = exceltools.new sheetInfo (); sheetinfo.setrowtitle (0); 맵 열 = New Hashmap (); columns.put ( "columns", new String [] { "name : case name", "violatelaw : 법의 브레이크", "punishbasis : punishbasis"}); sheetInfo.setColumnsMapping (열); 목록 <hashmap <string, string >> maplist = exceltools.getexcel (inputstream, sheetinfo); for (int i = 0; i <maplist.size (); i ++) {hashmap <string, String> map = maplist.get (i); 문자열 이름 = map.get ( "이름"); if (stringUtils.isempty (name)) {Throw New BusinessException ( "th" + (i + 2) + "케이스 이름이 비어있을 수 없음"); } String violationLaw = map.get ( "Violatelaw"); 문자열 처벌 바이스 = map.get ( "PunishBasis"); CISCASEACTION CISCASEACTION = NEW CISCASEACTION (); CISCASEACTION.SETNAME (이름); CISCASEACTION.SETVIOLATELAW (Violatelaw); CISCASEACTION.SETPUNISHBASIS (PUMISHBASIS); this.insert (ciscaseacect); // 동일한 레이어의 삽입 메소드 호출}} 위는이 기사의 모든 내용입니다. 모든 사람의 학습에 도움이되기를 바랍니다. 모든 사람이 wulin.com을 더 지원하기를 바랍니다.