1. Konzept Einführung
Apachepoi ist eine Open -Source -Bibliothek der Apache Software Foundation. POI bietet Java -Programmen APIs zum Lesen und Schreiben von Microsoft Office -Formatarchiven.
2. Funktionsbezogener Code
1. Umgebungsbeschreibung: JDK1.7+Tomcat7+Spring
2. Konfigurationsdateikonfiguration
Fügen Sie POI -Abhängigkeiten hinzu, die in der POM -Datei erforderlich sind
<!-poi-Unterstützung hinzufügen-> <depeaponcy> <GroupId> org.apache.poi </GroupId> <artifactId> poi </artifactId> <version> 3.13 </Version> </abhängig> <abhängigkeit> <gruppe org.
Spring-MVC.xml-Konfigurationsdatei Upload
<bean id = "multipartresolver"> <!-Standard-Codierung-> <Eigenschaft name = "DefaultCoding" value = "utf-8" /> <!-Maximaler Dateigrößenwert-> <Eigenschaft name = "MaxUploadsize" value = "1048576000000000000000000000000" /> <! </bean>
3.. Verwandte Werkzeugkurse und Code schreiben
Excel Parsing Tool Class (Importexcelutil.java)
Paket com.jointem.hrm.utils; import org.apache.poi.hssf.usmodel.hssfworkbook; import org.apache.poi.s.usmodel.cell; org.apache.poi.ss.usmodel.workbook; import org.apache.poi.s.util.cellrangeadress; import org.apache.poi.xssf.usermodel.xssfworkbook; import.iioxception; Java.Text.SimpledateFormat; Import Java.util.ArrayList; Import Java.util.List;/*** Erstellt von Jenking am 2017/9/8. */public class ImportExcelutil {private endgültige statische String excel2003l = ". xls"; // 2003- Version von Excel Private Final Static String excel2007u = ". Xlsx"; // 2007+ Version von Excel/** * Beschreibung: Holen Sie sich die Daten im IO -Stream und montieren Sie sie in eine Liste <list <objekt >> Objekt * @param in, Dateiname * @Return * @throws ioException */public liste <list <object >> getBankListByExcel (InputStream in, String FileName). // Excel Workbook Work = this.getworkbook (in, Dateiname) erstellen; if (null == Arbeit) {neue Ausnahme werfen ("Excel -Arbeitsblatt als leer erstellen!"); } Blatt = null; Row row = null; Zellzelle = NULL; list = new ArrayList <list <object >> (); // Ruhe alle Blätter in Excel für (int i = 0; i <work.getNumberofsheets (); i ++) {Sheet = work.getSheetat (i); if (Sheet == null) {Fortsetzung;} // Ruhe alle Zeilen im aktuellen Blattsystem.out.println (Sheet.getLastrownum ()); für (int j = sheet.getFirstrownum (); j <= Sheet.getLastrownum ()-11; j ++) {row = sheet.getRow (j); // if (row == null || row.getFirstcellnum () == j) // // Fortsetzung; für (int y = row.getFirstcellnum (); y <row.getLastcellnum (); y ++) {cell = row.getCell (y); if (this.isMergedRegion (Blatt, j, y)) {li.add (this.getMergedRegionValue (Blatt, j, y)); } else {li.add (this.getCellValue (Zelle)); }} list.add (li); }} work.close (); Rückgabeliste; } / ** * Beschreibung: Gemäß der Datei -Suffix hat die Version der Datei adaptivIver * @param instr, fileName * @return * @throws Exception * / public Workbook Getworkbook (InputStream Instree, String Dateiname) Auslöst Ausnahme {Workbook Wb = Null; String fileType = Dateiname.substring (Dateiname.lastIndexof (".")); if (excel2003l.equals (Filetype)) {wb = new HSSFWorkbook (Instrumente); // 2003-} else if (excel2007u.equals (Filetype)) {wb = new XSSFWorkbook (Instrumente); // 2007+} else {neue Ausnahme werfen ("Das Parsed -Dateiformat ist falsch!"); } return wb; } / ** * Beschreibung: Formatieren Sie die Werte in der Tabelle * @param cell * @return * / public Object getCellValue (Zellenzelle) {Object value = null; DecimalFormat df = new DecimalFormat ("0"); // Formatnummer String Zeichen SimpleDateFormat SDF = new SimpledateFormat ("yyy-mm-dd"); // Datumsformat Decimalformat df2 = neue DecimalFormat ("0"); // Formatnummer Switch (cell.getCellType ()) {case cell.cell_type_string: value = cell.getrichstringCellValue (). GetString (); brechen; case cell.cell_type_numeric: if ("allgemein" .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 ()); } brechen; case cell.cell_type_boolean: value = cell.getBooleancellValue (); brechen; case cell.cell_type_blank: value = ""; brechen; Standard: Break; } Rückgabewert; } / ** * Erhalten Sie den Inhalt der fusionierten Zelle * @Param Sheet * @param row * @param -Spalte * @return * / public Object getMergedRegionValue (Blattblatt, int Zeile, int Spalte) {int SheetmerGecount = Sheet.getNummerged Regions (); für (int i = 0; i <SheetmerGeCount; i ++) {CellRangeaddress Ca = Sheet.Getmergedregion (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 && Spalte <= lastColumn) {row frow = Sheet.getRow (firstrow); Cell fcell = frow.getCell (FirstColumn); return this.getCellValue (fcell); }} return null; } / ** * Bestimmen Sie, ob es sich um eine fusionierte Zelle handelt * @param Sheet * @param row * @param -Spalte * @return * / public boolean isMergedregion (Blattblatt, int Zeile, int Spalte) {int SheetmerGeCount = Sheet.getNummerged Regions (); für (int i = 0; i <SheetmerGeCount; i ++) {cellRangeaddress -Bereich = Sheet.GetMergedRegion (i); int firstColumn = Bereich.getFirstcolumn (); int lastcolumn = range.getLastcolumn (); int firstrow = Bereich.getFirStrow (); int lastrow = Bereich.getLastrow (); if (row> = firstrow && row <= lastrow) {if (column> = firstColumn && Spalte <= lastColumn) {return true; }}} return false; }} Request Controller (Prozessseite Excel Importanfrage)
Paket com.poiexcel.control; importieren java.io.inputstream; Import Java.io.printwriter; importieren java.util.list; importieren javax.servlet.http.httpServletRequest; importieren javax.servlet.http.httpServletResponse; import org.springframework.stereotype.controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.requestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.multipartFile; import org.springframework.web.multipart.multiparthttpServletRequest; import com.poiexcel.util.importexcelutil; import com.poiexcel.vo.infovo; @Controller @RequestMapPing ("/uploadexcel/ *") öffentliche Klasse UploadexcelControl {/** * Beschreibung: Importieren Sie die Excel -Datei über traditionelle Formulare * @param request * @throws Exception */@Requestmaping (value = "upload.do", Methode = {{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{Anfrage), requestMeth.get. uploadexcel (httpServletRequest Request) löst eine Ausnahme aus {multiparthttpServletRequest multipArtrEquest = (multiparthttpServletRequest) Anforderung; InputStream in = null; Liste <list <object >> listOb = null; MultiPartFile -Datei = multipArtrequest.getFile ("UpFile"); if (Datei.isempty ()) {neue Ausnahme werfen ("Datei nicht existiert!"); } in = file.getInputStream (); listOb = new ImportExcelutil (). getBankListByExcel (in, File.getOriginalFileName ()); in.close (); // Die entsprechende Servicemethode kann hier aufgerufen werden, um die Daten in der Datenbank zu speichern. Jetzt wird nur die Daten ausgegeben (int i = 0; i <listOb.size (); i ++) {list <element> lo = listOb.get (i); Infovo vo = new 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 ("Printinformation-> Institution:"+vo.getCode ()+"Name:"+vo.getName ()+"Zeit:"+vo.getDate ()+"Asset:"+vo.getMoney ()); } return "result"; } Front-End-Code
Das Front-End verwendet die Datei-Upload-Komponent-Datei -Input von Bootstrap und muss FileInput.css, FileInput.js, Zh.js, Bootstrap.css, Bootstrap.js, jquery.min.js einführen
<body> <h4> Anwesenheitsinformationen Eintrag </h4> <Formmethode = "post" engType = "multiPart/form-data" id = "Form1" action = "$ {pageContext.request.ContextPath}/Anwesenheit/Uplloadexcel"> <input id = "file-zh" namens $ ('#File-Zh'). FileInput ({Sprache: 'Zh', Uploadurl: '$ {pageContext.Request.ContextPath}/Anwesenheit/uploadexcel', erlaubteFilextensionen: ['xls', 'xlsx']}); VO -Objekt, speichern Sie das entsprechende Objekt der Excel -Daten
Paket com.poiexcel.vo; // jede Zeile von Excel in ein Objekt in Infovo {private String -Code in ein Objekt umwandeln; privater Zeichenfolge Name; privates Zeichenfolgendatum; privates Stringgeld; public String getCode () {return code; } public void setCode (String -Code) {this.code = code; } public String getName () {return name; } public void setName (String -Name) {this.name = name; } public String getDate () {Rückgabedatum; } public void setDate (String Datum) {this.date = Datum; } public String getMoney () {Return Money; } public void setMoney (String Money) {this.money = enden; }}3. Effektanzeige
1. Seitenanzeige
2. Backend -Informationen drucken
4. Zusammenfassung
Dieses Beispiel gibt nur die importierten Daten in der Konsole aus und bleibt nicht bestehen. Wenn Sie bestehen bleiben möchten, rufen Sie einfach die Serviceschicht am Kommentarort an
Das obige ist der gesamte Inhalt dieses Artikels. Ich hoffe, es wird für das Lernen aller hilfreich sein und ich hoffe, jeder wird Wulin.com mehr unterstützen.