Package poi;
Import Java.io.FileInputStream;
Import java.io.IOException;
Import Java.io.InputStream;
Import Java.util.Iterator;
Import Org.apache.poi.hssf.usermodel.HSSFCell;
Import Org.apache.poi.hssf.usermodel.HSSFWorkbook;
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.xssf.usermodel.XSSFWorkbook;
public class ReadExcel001 {
public static void Main (string[] args) {
READXML ("d:/test.xlsx");
System.out.println ("-------------");
READXML ("D:/test2.xls");
}
public static void ReadXml (String fileName) {
Boolean isE2007 = false; Determine if the format is excel2007
if (Filename.endswith ("xlsx"))
isE2007 = true;
try {
InputStream input = new FileInputStream (fileName); Create an input stream
Workbook wb = null;
Class according to the file format (2003 or 2007)
if (isE2007)
WB = new Xssfworkbook (input);
Else
WB = new Hssfworkbook (input);
Sheet Sheet = wb.getsheetat (0); Get the first form
iterator<row> rows = Sheet.rowiterator (); The iterator that gets the first form
while (Rows.hasnext ()) {
Row row = Rows.next (); Get Row data
System.out.println ("Row #" + row.getrownum ()); Get line number starting from 0
Iterator<cell> cells = Row.celliterator (); Get the first line of iterators
while (Cells.hasnext ()) {
Cell cell = Cells.next ();
System.out.println ("Cell #" + Cell.getcolumnindex ());
Switch (Cell.getcelltype ()) {//output data according to the type in the cell
Case Hssfcell.cell_type_numeric:
System.out.println (Cell.getnumericcellvalue ());
Break
Case hssfcell.cell_type_string:
System.out.println (Cell.getstringcellvalue ());
Break
Case Hssfcell.cell_type_boolean:
System.out.println (Cell.getbooleancellvalue ());
Break
Case Hssfcell.cell_type_formula:
System.out.println (Cell.getcellformula ());
Break
Default
SYSTEM.OUT.PRINTLN ("unsuported sell type");
Break
}
}
}
} catch (IOException ex) {
Ex.printstacktrace ();
}
}
}
Reprint Java reads Excel 2010 using poi.3.10