예 : 관련 데이터 가져 오기 (Excel 파일) 및 관련 파일 데이터를 편집하십시오.
XML 파일 구성
그런 다음 스프링 XML 파일에 업로드 할 파일의 크기를 구성합니다.
<!-파일 인터 컨셉 업로드, 최대 업로드 파일 크기를 설정하십시오. 파일 크기 10m = 10*1024*1024 (b) = 10485760 바이트-> <bean id = "multipartresolver"> <속성 이름 = "maxUploadSize"value = "10485760" />>>
JSP 인터페이스 구성
<div> <form id = "sourcefile"name = "sourcefile"action = ""method = "post"encticpe = "multipart /form-data"> <입력 유형 = "value ="add "onclick ="addairline () "" /> <입력 스타일 = "margin-left : 20px;" id = "source_file"name = "sourcefile"type = "file"value = "파일 선택" /> <입력 스타일 = "마진-왼쪽 : 20px;" data-loading-text = "반복적으로 제출하지 마십시오"type = "제출"value = "upload"onclick = "uppolicy ()"> <input style = "margin-left : 20px;" type = "value ="value = "다운로드 템플릿"onclick = "return downloadtemplate ();"> </form> </div>
JS 파일
function uppolicy () {document.sourcefile.action = "/login/policy/uploadcsv"; var submiturl = document.getElementById ( "SourceFile"). 속성 [ "action"]. value; $ .ajax ({type : "post", url : dataM : $ ( '##sourcefile'). serialize (), datatype : "json", success : function (var json = json.parse (result); if (json.flag = "0"|| json.flag == "1") {tablejson. }컨트롤러 구성
@RequestMapping (value = "/uploadcsv", method = requestmethod.post) @ResponseBody public string uploadcsv (@requestParam ( "sourceFile") multipartFile SourceFile, httpservletRequest request) IoException {// retect in (httpservletResponse resigins responsk) {//가 님이 비어있는 경우 (httpservletResponse 응답) // 파일 이름을 가져옵니다. string name = sourceFile.GetorIginalFilename (); // 파일이 비어 있는지 여부를 추가로 결정하십시오 (즉, 크기가 0인지 또는 이름이 null인지 확인) long size = sourcefile.getSize (); if (name == null || ( ""). Equals (name) && size == 0) return null; // 배치 가져 오기. 매개 변수 : 파일 이름, 파일 부울 B = 배치 림 (이름, SourceFile); jsonobject jsonobject = new jsonobject (); if (b) {jsonobject.put ( "flag", 0); jsonobject.put ( "성공", "배치 가져 오기 Excel!"); } else {jsonobject.put ( "flag", 1); jsonobject.put ( "성공", "배치 가져 오기 Excel 실패!"); } return JsonObject.toString (); }레이어링은 그다지 상세하지 않으며 컨트롤러에서 처리됩니다.
Public Boolean Batchimport (문자열 이름, multipartfile 파일) {boolean b = false; // Excelutils ReadExcel = New Excelutils (); // 엑셀을 구문 분석하고 고객 정보 모음을 얻습니다. 목록 <Otapolicymodel> cpolicylist = readexcel.getexcelinfo (이름, 파일); if (cpolicylist! = null) {b = true; } // 반복적으로 정보 추가 (참고 : 실제로 CPOLCYLIST 세트를 매개 변수로 직접 사용하고 Foreach 태그를 사용하여 배치 추가를 위해 MyBatis의 해당 매핑 파일을 추가 할 수 있습니다.) } 반환 b; }도구 클래스 Excelutils.java
즉, readexcel.getexcelinfo (이름, 파일)가 호출하는 메소드; 위의 방법 및 기타 관련 방법의 명령문
Apache Poi는 Microsoft Office Format Archives를 읽고 작성하기 위해 API에서 Java 프로그램을 제공합니다. 그러나 우선 Excel 버전을 판단하고 다른 통합 문서를 선택해야합니다 (2003 버전은 HSSFWorkbook에 해당하고 2007 버전 이상은 XSSFWorkbook에 해당합니다). 또한 일반적으로 말하면 먼저 클라이언트 사용자가 업로드 한 파일을 서버의 로컬 디스크에 복사 한 다음이 복사 파일에서 읽어서 네트워크 예외 또는 클라이언트의 다른 조건으로 인해 읽기 중 데이터 손실 또는 손상을 피하십시오.
package com.flight.inter.otaadapter.commons.util; import com.flight.inter.otaadapter.model.otapolicymodel; import org.apache.poi.hsssf.usermodel.hssfworkbook; import org.apache.poi.ss.usermodel.cell; import org org.apache.poi.ss.usermodel.sheet; import org.apache.poi.ss.usermodel.workbook; import org.apache.poi.xssf.usermodel.xssfworkbook; import org.spramframework.web.multipart.multipartfile; import org.springframework.web.multipart.commons.commonsmultipartfile; import java.io.*; import java.math.bigdecimal; import java.util.arraylist; import java.util.date; import java.util.list;/*** Ling.zhang에 의해 생성되었습니다. */public class Excelutils {// 총 행 수 개인 int totalrows = 0; // 총 조각 수 개인 int totalcells = 0; // 오류 메시지 수신자 private String errormsg; // 구성 방법 public ExcelUtils () {} // 총 행 번호 가져 오기 공개 int getTotalrows () {return totalrows;} // 총 열 수 받기 public int getTotalCells () {return totalcells;} // 오류 메시지 공개 문자열 geterRorInfo () {return errormsg; } / ** * Excel 파일 확인 * @param filepath * @return * / public boolean validateExcel (string filepath) {if (filepath == null ||! 거짓을 반환합니다. } true를 반환합니다. } /** * Excel 파일을 읽고 고객 정보 수집을 받고 고객 정보 수집 * @param * /public List <OtapolicyModel> getExcelInfo (String filename, multipartfile mfile) {// spring 파일에 의해 업로드 된 multipartFile 유형 CommonSmultItFile CF = (CommonSmmultItFile); // 로컬 스토리지 경로 가져 오기 파일 = 새 파일 ( "d : // fileUpload"); // 디렉토리 생성 (PathName은 필요한 부모 경로를 포함하여 현재 파일 객체에 의해 지정됩니다.) if (! file.exists ()) file.mkdirs (); // 새 파일을 생성 파일 파일 1 = 새 파일 ( "d : // fileUpload" + new date (). gettime () + ".xlsx"); // 업로드 된 파일을 새로 작성된 파일에 쓰기 {cf.getFileItem (). 쓰기 (file1); } catch (예외 e) {e.printstacktrace (); } // 고객 정보 목록 모음을 초기화합니다 <OtapolicyModel> customerList = new ArrayList <OtapolicyModel> (); // 입력 스트림 초기화 입력 스트림은 = null; {// 파일 이름이 자격이 있는지 확인하십시오. } // 파일이 버전 2003인지 또는 파일 이름을 기준으로 2007 년 버전 인 Boolean ISEXCEL2003 = true; if (wdwutil.isexcel2007 (filename)) {isexcel2003 = false; } // 새로 생성 된 파일에 따라 입력 스트림을 인스턴스화합니다. // Excel의 컨텐츠를 기반으로 고객 정보를 읽으십시오. 고객은 GetExcelInfo (IS, ISEXCel2003); is.close (); } catch (예외 e) {e.printstacktrace (); } 마침내 {if (is! = null) {try {is.close (); } catch (ioexception e) {is = null; e.printstacktrace (); }} Reftent CustomerList를 반환합니다. } / *** Excel의 컨텐츠를 기반으로 고객 정보 읽기* @param IS 입력 스트림* @param isexcel2003은 Excel 2003 또는 2007 버전* @return* @throws ioexception* / public list <otapolicymodel> getexcelinfo (inputstream is, boolean isexcel2003) {otapolicymodel rist = null; 시도 { / ** 버전* / 통합 문서 WB = NULL에 따라 통합 문서를 만드는 방법을 선택하십시오. // Excel이 2003 인 경우 (ISEXCEL2003) {WB = NEW HSSFWORKBOOK (IS); } else {// Excel이 2007 일 때 WB = New XSSFWorkBook (IS); } // Excel CustomerList = readExcelValue (WB)에서 고객의 정보를 읽습니다. } catch (ioexception e) {e.printstacktrace (); } Reftent CustomerList를 반환합니다. } /** * Excel * @param wb * @return * /private list <OtapolicyModel> readExcelValue (workbook wb) {// 첫 번째 쉘 시트를 얻습니다. wb.getsheetat (0); // Excel에서 행의 수를 가져옵니다 .totalrows = sheet.getPhysicalNumberOfrows (); // excel에서 열 수를 가져옵니다 (아마도 행 } list <Otapolicymodel> otapolicymodellist = new arraylist <Otapolicymodel> (); otapolicymodel otapolicymodel; // 두 번째 줄에서 시작하여 Excel 행 번호를 루프합니다. 제목은 (int r = 1; r <totalrows; r ++)에 저장되지 않습니다. {row row = sheet.getrow (r); if (row == null) 계속; otapolicymodel = 새로운 otapolicymodel (); try {thread.currentthread (). sleep (1); } catch (InterruptedException e) {e.printstacktrace (); } otapolicymodel.setpolicyid (System.CurrentTimeMillis ()); // (int c = 0; c <this.totalCells; c ++) {cell cell = row.getCell (c); if (null! = cell) {if (c == 0) {otapolicymodel.setSource (cell.getStringCellValue ()); // supplier} else if (c == 1) {otapolicyModel.setVendee (cell.getStringCellValue ()); else (c = int trippe = 0)}; if (cell.getStringCellValue () == "all") {Triptype = 0; } else if (cell.getStringCellValue (). Equals ( "단일 웨이")) {Triptype = 10; } else if (cell.getStringCellValue (). Equals ( "왕복")) {Triptype = 20; } else if (cell.getStringCellValue (). Equals ( "단일 방향 직접 비행")) {Triptype = 11; } else if (cell.getStringCellValue (). Equals ( "왕복")) {Triptype = 12; } else if (cell.getStringCellValue (). Equals ( "왕복")) {Triptype = 21; } else if (cell.getStringCellValue (). Equals ( "왕복")) {Triptype = 21; } else if (cell.getStringCellValue (). Equals ( "왕복")) {Triptype = 22; } otapolicymodel.settriptype (triptype); // virtinerary type} else if (c == 3) {otapolicymodel.setCarrier (cell.getStringCellValue ()); // airline code} else if (c == 4) {otapolicymodel.setepcity (cell.getstringccity); City} else if (c == 5) {otapolicymodel.setArrcity (cell.getStringCellValue ()); // Landing City} else if (c == 6) {otapolicymodel.setsalebegindatel (new bigdecimal (cell.getnumericcellValue ()). setScale (0, bigdecimal.round_half_down) .longValue ()); // 판매 시작 날짜} else if (c == 7) {otapolicymodel.setsaleenddatel (new bigdecimal (cell.getnumericcellvalue ()). setScale (0, bigdecimal.round_half_down) .longValue ()); // 판매 종료 날짜} else if (c == 8) {otapolicymodel.settravelbegindatel (new bigdecimal (cell.getnumericcellValue ()). setScale (0, bigdecimal.round_half_down) .longValue ()); // 여행 시작 날짜} else if (c == 9) {otapolicymodel.setTravelendDatel (new bigdecimal (cell.getnumericcellvalue ()). setScale (0, bigdecimal.round_half_down) .longValue ()); // travel end date} else if (c == 10) {int cabintype = 9; if (cell.getStringCellValue (). equals ( "all")) {cabintype = 9; } else if (cell.getStringCellValue (). Equals ( "Economy Class")) {cabintype = 1; } else if (cell.getStringCellValue (). equals ( "business")) {cabintype = 2; } else if (cell.getStringCellValue (). Equals ( "First Class")) {cabintype = 3; } otapolicymodel.setcobintype (cabintype); // dargrift level} else if (c == 11) {otapolicymodel.setfdtype (cell.getStringCellValue (). otapolicymodel.setcabin (cell.getStringCellValue ()); // cat} else if (c == 13) {otapolicymodel.setpricebegin (cell.getnumericcellValue ()); // 최소 가격} else if (c == 14) { otapolicymodel.setpriceend (cell.getnumericcellvalue ()); // 최대 가격} else if (c == 15) {otapolicymodel.setlmoney (cell.getnumericcellValue ()); // 돈을 저장} else if (c == 16) { otapolicymodel.setfpercent (cell.getnumericcellvalue ()); // 전체 가격 리베이트} else if (c == 17) {otapolicymodel.setftpercent (cell.getNumericCellValue ()); // if (c == 18) {int carrerlimit = 2; if (cell.getStringCellValue (). equals ( "yes")) {carrierLimit = 1; } else if (cell.getStringCellValue (). equals ( "no")) {carrierLimit = 0; } else if (cell.getStringCellValue (). Equals ( "none")) {carriplimit = 2; } otapolicymodel.setCarrierLimit (carrierLimit); // 송장 항공 제한} else if (c == 19) {int transport = 2; if (cell.getStringCellValue (). Equals ( "yes")) {ranvert = 1; } else if (cell.getStringCellValue (). Equals ( "no")) {ranvert = 0; } else if (cell.getStringCellValue (). Equals ( "no")) {ranvert = 0; } else if (cell.getStringCellValue (). Equals ( "no")) {ranvert = 0; } else if (cell.getStringCellValue (). Equals ( "no")) {ranvert = 0; } else if (cell.getStringCellValue (). Equals ( "no")) {ranvert = 0; } else if (cell.getStringCellValue (). Equals ( "no")) {ranvert = 0; } else if (cell.getStringCellValue (). Equals ( "Unlimited")) {ranvert = 2; } otapolicymodel.setTransport (Transport); // 인터 모달 전송 지원} else if (c == 20) {int sharedflight = 2; if (cell.getStringCellValue (). equals ( "yes")) {sharedflight = 1; } else if (cell.getStringCellValue (). Equals ( "no")) {sharedflight = 0; } else if (cell.getStringCellValue (). Equals ( "none")) {sharedflight = 2; } otapolicymodel.setsharedflight (sharedflight); // 공유 비행 지원} else if (c == 21) {otapolicymodel.setpstatus (cell.getStringCellValue (). if (cell.getStringCellValue (). Equals ( "private")) {faretype = 1; } else if (cell.getStringCellValue (). Equals ( "publication")) {faretype = 2; } else if (cell.getStringCellValue (). Equals ( "publication")) {faretype = 2; } else if (cell.getStringCellValue (). Equals ( "all")) {faretype = 0; } otapolicymodel.setfaretype (faretype); // freight type} else if (c == 23) {otapolicymodel.setLimitPrice (new bigdecimal (cell.getNumericCellValue ()). setScale (0, bigdecimal.round_half_down) if (c == 24) {int limittransit = 2; if (cell.getStringCellValue (). equals ( "all")) {limittransit = 2; } else if (cell.getStringCellValue (). Equals ( "applicate")) {limittransit = 0; } else if (cell.getStringCellValue (). Equals ( "적용 가능")) {limittransit = 1; } otapolicymodel.setlimittransit (limittransit); // 전환 한계} else if (c == 25) {otapolicymodel.setArrcity (cell.getStringCellValue ()); if (cell.getStringCellValue (). equals ( "all")) {limitnation = 2; } else if (cell.getStringCellValue (). equals ( "applicate")) {limitnation = 0; } else if (cell.getStringCellValue (). equals ( "적용 할 수 없음")) {limitnation = 1; } otapolicymodel.setlimitnation (limitnation); // 국적 한계} else if (c == 27) {otapolicymodel.setArrcity (cell.getStringCellValue ()); // 국적} else if (c == 28) {otapolicymodel.setusername (cell.ggetStringcell value el) } // 고객 추가 otapolicymodellist.add (otapolicymodel); } otapolicymodellist를 반환합니다. }}도구 클래스 wdwutil.java
package com.flight.inter.otaadapter.commons.util;/*** 2016/12/29에 Ling.zhang에 의해 만들어졌습니다. */ public class wdwutil {// @description : 2003 년의 Excel이든 Return true는 2003 Public STATIC BOOLEAN ISEXCEL2003 (String FilePath) {return filePath.Matches ( "^.+/. (? i) (xls) $"); } //@description : 2007 년의 Excel이든 Return True는 2007public static boolean isexcel2007 (String Filepath) {return filepath.matches ( "^.+//. (? i) (xlsx) $");}}참고 : 읽기 편의성을 위해 위의 코드는 먼저 부모 메소드와 자식 방법으로 게시됩니다. 실제 코드 편집에서 자식 메소드는 일반적으로 먼저 편집 한 다음 부모 메소드로 편집됩니다. 예를 들어, 위는 먼저 도구 클래스 코드를 편집 한 다음 서비스 계층 코드를 편집하고 마지막으로 컨트롤러 코드를 편집해야합니다.
이런 식으로 전체 프로세스는 괜찮습니다. 지금 테스트하기 위해 가져 가십시오
보다 흥미로운 콘텐츠는 심층적 인 연구 및 연구를 위해 "스프링 업로드 및 특별 주제 다운로드"를 클릭하십시오.
위는이 기사의 모든 내용입니다. 모든 사람의 학습에 도움이되기를 바랍니다. 모든 사람이 wulin.com을 더 지원하기를 바랍니다.