First, go to the poi official website http://poi.apache.org/to download the latest version of the poi package. The latest version is 3.9.
Excel requires the following JAR packages:
Then, import the jar package in the Java project.
The Code is as follows:
Import Java. io. fileinputstream; import Java. io. filenotfoundexception; import Java. io. ioexception; import Java. io. inputstream; import Java. util. arraylist; import Java. util. iterator; import Java. util. list; import Org. apache. poi. hssf. usermodel. hssfworkbook; import Org. apache. poi. xssf. usermodel. xssfworkbook; import Org. apache. poi. SS. usermodel. cell; import Org. apache. poi. SS. usermodel. dateutil; import Org. apache. po I. SS. usermodel. row; import Org. apache. poi. SS. usermodel. sheet; import Org. apache. poi. SS. usermodel. workbook; public class main {public static void main (string [] ARGs) {inputstream in = NULL; workbook WB = NULL; string Path = "C: \ Users \ CHT \ Desktop \ test.xlsx "; try {In = new fileinputstream (PATH); If (path. endswith (". xls ") WB = new hssfworkbook (in); If (path. endswith (". XLSX ") WB = new xssfworkbook (in); int Sheetnum = WB. getnumberofsheets (); If (sheetnum = 0) return; For (INT I = 0; I <sheetnum; I ++) {sheet = WB. getsheetat (I); iterator <row> iterrow = sheet. rowiterator (); While (iterrow. hasnext () {row = iterrow. next (); iterator <cell> itercell = row. celliterator (); While (itercell. hasnext () {Cell cell = itercell. next (); system. out. println (getcellvalue (cell) ;}}} catch (filenotfoundexception fnfe X) {// throw fnfex;} catch (ioexception ioex) {// throw ioex;} finally {try {In. close ();} catch (exception ex) {}}/ ***** obtain the value of each excel cell ** @ Param cell * @ return cell content */Private Static string getcellvalue (cell) {string val = NULL; Switch (cell. getcelltype () {Case cell. cell_type_string: val = cell. getrichstringcellvalue (). getstring (); break; Case cell. cell_type_numeric: If (dateutil. iscelld Ateformatted (cell) {val = cell. getdatecellvalue (). togmtstring ();} else {double D = cell. getnumericcellvalue (); val = string. valueof (d); int Index = Val. indexof (". "); If (-1! = Index) {val = Val. substring (0, index) ;}} break; Case cell. cell_type_boolean: val = string. valueof (cell. getbooleancellvalue (); break; Case cell. cell_type_formula: val = cell. getcellformula (); break; default:} return Val ;}}
If you operate the. xls file, you only need the following jar package.