Java read-write Excel package is Apache POI (Project address: http://poi.apache.org/), so you need to obtain the POI jar package, this experiment is using the POI 3.9 stable version.
Apache POI code example address: http://poi.apache.org/spreadsheet/quick-guide.html
This example reads Microsoft Office Excel 2003/2007/2010, with specific code and comments as follows:
read the ". xls" format using the import org.apache.poi.hssf.usermodel.*; package contents, for example: Hssfworkbook
Read the ". xlsx" format using the import org.apache.poi.xssf.usermodel.*; The contents of the package, for example: Xssfworkbook
Read both formats using the contents of the import org.apache.poi.ss.usermodel.* package, for example: Workbook
The introduction package is as follows:
Import Org.apache.poi.ss.usermodel.Cell;
Import Org.apache.poi.ss.usermodel.Row;
Import Org.apache.poi.ss.usermodel.Sheet;
Import Org.apache.poi.ss.usermodel.Workbook;
Import org.apache.poi.ss.usermodel.WorkbookFactory;
Import Org.apache.poi.ss.usermodel.DateUtil;
/** * Read Excel test, compatible with Excel 2003/2007/2010 */public String Readexcel () {SimpleDateFormat FMT
= new SimpleDateFormat ("Yyyy-mm-dd");
try {//also supports Excel 2003, 2007 File Excelfile = new file ("/home/zht/test.xls");//Create Files Object FileInputStream is = new FileInputStream (excelfile); File Stream Workbook workbook = Workbookfactory.create (IS); This way Excel 2003/2007/2010 can be handled by int sheetcount = Workbook.getnumberofsheets (); Number of Sheet//traversal of each Sheet for (int s = 0; s < sheetcount; s++) {Sheet Sheet = Wor
Kbook.getsheetat (s); int rowcount = Sheet.getphysicalnumberofrows (); Gets the total number of rows//traverses each line for (int r = 0; r < rowcount; r++) {Row row = Shee
T.getrow (R); int cellcount = Row.getphysicalnumberofcells (); Gets the total number of columns//traversal for each column for (int c = 0; C < CELLCOunt;
C + +) {cell cell = Row.getcell (c);
int celltype = Cell.getcelltype ();
String cellvalue = null; Switch (celltype) {case cell.cell_type_string://Text Cellvalue
= Cell.getstringcellvalue ();
Break
Case Cell.cell_type_numeric://number, date if (dateutil.iscelldateformatted (Cell)) { Cellvalue = Fmt.format (Cell.getdatecellvalue ()); Date type} else {Cellval UE = String.valueof (Cell.getnumericcellvalue ());
Number} break; Case Cell.cell_type_boolean://Boolean cellvalue = String.valueof (Cell.getbooleancellValue ());
Break
Case Cell.cell_type_blank://Blank cellvalue = Cell.getstringcellvalue ();
Break
Case CELL.CELL_TYPE_ERROR://Error Cellvalue = "Error";
Break
Case Cell.cell_type_formula://Formula Cellvalue = "Error";
Break
Default:cellvalue = "Error";
} System.out.print (Cellvalue + "");
} System.out.println ();
A catch (Exception e) {e.printstacktrace ());
return action.success; }