Hi all,
I am using eclipse ide on my windows XP 32 bit operating system to develop Java programs.
I am looking for a Java code which can read data from ms excel.
Any Java expert please tell me how to get excel data by eclipse and also share the source code.
Thanks.
How to get excel data by eclipse ide?
Hi Timothy,
You will need Java JDK 1.5 or above, Apache POI library v3.8 or above and Eclipse 3.2 above. At first include apache poi jar file to your project.
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.8</version>
</dependency>
Here is the sample code which will read data from Excel:
How to get excel data by eclipse ide?
Hi Timothy Raine,
Here is the source code for your program,
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
//..
FileInputStream file = new FileInputStream(new File("C:\test.xls"));
//Get the workbook instance for XLS file
HSSFWorkbook workbook = new HSSFWorkbook(file);
//Get first sheet from the workbook
HSSFSheet sheet = workbook.getSheetAt(0);
//Get iterator to all the rows in current sheet
Iterator<Row> rowIterator = sheet.iterator();
//Get iterator to all cells of current row
Iterator<Cell> cellIterator = row.cellIterator();
Let's consider simple excel file
We will read above xls file and prints the data.
try {
FileInputStream file = new FileInputStream(new File("C:\test.xls"));
//Get the workbook instance for XLS file
HSSFWorkbook workbook = new HSSFWorkbook(file);
//Get first sheet from the workbook
HSSFSheet sheet = workbook.getSheetAt(0);
//Iterate through each rows from first sheet
Iterator<Row> rowIterator = sheet.iterator();
while(rowIterator.hasNext()) {
Row row = rowIterator.next();
//For each row, iterate through each columns
Iterator<Cell> cellIterator = row.cellIterator();
while(cellIterator.hasNext()) {
Cell cell = cellIterator.next();
switch(cell.getCellType()) {
case Cell.CELL_TYPE_BOOLEAN:
System.out.print(cell.getBooleanCellValue() + "tt");
break;
case Cell.CELL_TYPE_NUMERIC:
System.out.print(cell.getNumericCellValue() + "tt");
break;
case Cell.CELL_TYPE_STRING:
System.out.print(cell.getStringCellValue() + "tt");
break;
}
}
System.out.println("");
}
file.close();
FileOutputStream out =
new FileOutputStream(new File("C:\test.xls"));
workbook.write(out);
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Output
Emp Id Name Salary
1.0 John 2000000.0
2.0 Dean 420000.0
3.0 Sam 280000.0
4.0 Cass 6000000.0
Hope this helps you.
Thanks,
|
|