import
java.io.File;
import
java.io.FileInputStream;
import
java.io.IOException;
import
java.util.ArrayList;
import
java.util.Iterator;
import
java.util.List;
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;
class
Employee {
private
String employeeName;
private
String employeeDesignation;
private
double
salary;
public
Employee() {}
public
String toString()
{
return
String.format(
"%s - %s - %f"
, employeeName,
employeeDesignation, salary);
}
public
String getEmployeeName() {
return
employeeName; }
public
void
setEmployeeName(String employeeName)
{
this
.employeeName = employeeName;
}
public
String getEmployeeDesignation()
{
return
employeeDesignation;
}
public
void
setEmployeeDesignation(String employeeDesignation)
{
this
.employeeDesignation = employeeDesignation;
}
public
double
getSalary() {
return
salary; }
public
void
setSalary(
double
d) {
this
.salary = d; }
}
public
class
GetContentFromExcelSheets {
private
Object getCellValue(Cell cell)
{
switch
(cell.getCellType()) {
case
Cell.CELL_TYPE_STRING:
return
cell.getStringCellValue();
case
Cell.CELL_TYPE_BOOLEAN:
return
cell.getBooleanCellValue();
case
Cell.CELL_TYPE_NUMERIC:
return
cell.getNumericCellValue();
}
return
null
;
}
public
List<Employee>
readBooksFromExcelFile(String excelFilePath)
throws
IOException
{
List<Employee> listEmployees
=
new
ArrayList<Employee>();
FileInputStream inputStream
=
new
FileInputStream(
new
File(excelFilePath));
Workbook workbook =
new
XSSFWorkbook(inputStream);
Sheet firstSheet = workbook.getSheetAt(
0
);
Iterator<Row> iterator = firstSheet.iterator();
while
(iterator.hasNext()) {
Row nextRow = iterator.next();
Iterator<Cell> cellIterator
= nextRow.cellIterator();
Employee emp =
new
Employee();
while
(cellIterator.hasNext()) {
Cell nextCell = cellIterator.next();
int
columnIndex = nextCell.getColumnIndex();
switch
(columnIndex) {
case
1
:
emp.setEmployeeName(
(String)getCellValue(nextCell));
break
;
case
2
:
emp.setEmployeeDesignation(
(String)getCellValue(nextCell));
break
;
case
3
:
emp.setSalary(Double.valueOf(
(String)getCellValue(nextCell)));
break
;
}
}
listEmployees.add(emp);
}
((FileInputStream)workbook).close();
inputStream.close();
return
listEmployees;
}
public
static
void
main(String[] args)
{
GetContentFromExcelSheets getContentFromExcelSheets
=
new
GetContentFromExcelSheets();
List<Employee> extractedEmployeeData
=
new
ArrayList<Employee>();
try
{
extractedEmployeeData
= getContentFromExcelSheets
.readBooksFromExcelFile(
"excelFileContents.xlsx"
);
}
catch
(IOException e) {
e.printStackTrace();
}
System.out.println(extractedEmployeeData);
}
}