1//You need Apache POI library in order to work this code
2
3//Using Apache POI
4 import java.io.File;
5 import java.io.FileInputStream;
6 import java.io.IOException;
7 import org.apache.poi.hssf.usermodel.HSSFSheet;
8 import org.apache.poi.hssf.usermodel.HSSFWorkbook;
9 import org.apache.poi.ss.usermodel.Cell;
10 import org.apache.poi.ss.usermodel.FormulaEvaluator;
11 import org.apache.poi.ss.usermodel.Row;
12 public class ReadExcelFileDemo
13 {
14 public static void main(String args[]) throws IOException
15 {
16 //obtaining input bytes from a file
17 FileInputStream fis=new FileInputStream(new File("C:\\demo\\student.xls"));
18 //creating workbook instance that refers to .xls file
19 HSSFWorkbook wb=new HSSFWorkbook(fis);
20 //creating a Sheet object to retrieve the object
21 HSSFSheet sheet=wb.getSheetAt(0);
22 //evaluating cell type
23 FormulaEvaluator formulaEvaluator=wb.getCreationHelper().createFormulaEvaluator();
24 for(Row row: sheet) //iteration over row using for each loop
25 {
26 for(Cell cell: row) //iteration over cell using for each loop
27 {
28 switch(formulaEvaluator.evaluateInCell(cell).getCellType())
29 {
30 case Cell.CELL_TYPE_NUMERIC: //field that represents numeric cell type
31 //getting the value of the cell as a number
32 System.out.print(cell.getNumericCellValue()+ "\t\t");
33 break;
34 case Cell.CELL_TYPE_STRING: //field that represents string cell type
35 //getting the value of the cell as a string
36 System.out.print(cell.getStringCellValue()+ "\t\t");
37 break;
38 }
39 }
40 System.out.println();
41 }
42 }
43 }