You first need to introduce the following jar packages
If you use MAVEN, you need to add two dependencies
<Dependencies> <Dependency> <groupId>Org.apache.poi</groupId> <Artifactid>Poi</Artifactid> <version>3.15</version> </Dependency> <Dependency> <groupId>Org.apache.poi</groupId> <Artifactid>Poi-ooxml</Artifactid> <version>3.15-beta2</version> </Dependency> </Dependencies>
Excel is divided into two kinds of suffixes, one is XLS and the other is xlsx.
First, the XLS format for Excel is parsed:
Public List<String[]>readexcel (file file) {List<String[]>List = new ArrayList<>(); try {hssfworkbook hw = new Hssfworkbook (new FileInputStream (file)); for (int i = 0; I<hw.getnumberofsheets(); i++) {Hssfsheet HS= Hw.getsheetat (i);if (Hs.getlastrownum ()== 0) Continue; for (Int J= 0;J <= Hs.getlastrownum ();J + +) {//Hssfrow row= Hs.getrow (j); string[] Array= newString[row.getlastcellnum ()]; for (int k= 0;K < Row.getlastcellnum (); k++) {Hssfcell cell= Row.getcell (k); Array[k]= This.getvalue (cell); } list.add (array); }}} catch (IOException e) {e.printstacktrace (); } return list; } private String GetValue (Hssfcell cell) {String value; Celltype type= Cell.getcelltypeenum (); switch (type) {case String:value= Cell.getstringcellvalue (); Break ; Case Blank:value= ""; Break Case Boolean:value= Cell.getbooleancellvalue ()+ ""; Break Case Numeric:value= Cell.getnumericcellvalue ()+ ""; Break Case Formula:value= Cell.getcellformula (); Break ; Case Error:value= "illegal character"; Break Default:value= ""; Break } return value; }
For the xlsx format Excel, the difference between the hssf*** and the above is to replace the xssf*** with the following example:
Public List<String[]>readexcel (file file) {List<String[]>List = new ArrayList<>(); try {xssfworkbook XW = new Xssfworkbook (new FileInputStream (file)); for (int i = 0; I<xw.getnumberofsheets(); i++) {xssfsheet xs= Xw.getsheetat (i); if (Xs.getlastrownum ()== 0) Continue; for (Int J= 0;J <= Xs.getlastrownum ();J + +) {Xssfrow row= Xs.getrow (j); string[] Array= newString[row.getlastcellnum ()]; for (int k= 0;K <= Row.getlastcellnum ();k++) {Xssfcell cell= Row.getcell (k); if (cell== null) continue; ARRAY[K]= This.getvalue (cell); } list.add (array); }}} catch (IOException e) {e.printstacktrace (); } return list; } private String GetValue (Xssfcell cell) {String value; Celltype type= Cell.getcelltypeenum (); switch (type) {case String:value= Cell.getstringcellvalue (); Break ; Case Blank:value= ""; Break Case Boolean:value= Cell.getbooleancellvalue ()+ ""; Break Case Numeric:value= Cell.getnumericcellvalue ()+ ""; Break Case Formula:value= Cell.getcellformula (); Break ; Case Error:value= "illegal character"; Break Default:value= ""; Break } return value; }
Java parsing Excel files with POI