I am able to read the excel file data from the below code, but i am unable to get the logic behind how to get excel data in order to store in POJO class after reading the excel file. In short: I have confusion on how to send these read excel data to my model class to be stored in my Database table?
The following code prints correctly the excel rows in my Eclipse Console:
..............
..............
public String execute()
{
try
{
String filePath=servletRequest.getSession().getServletContext().getRealPath("/");
File fileToCreate= new File(filePath,this.excelDataFileName);
FileUtils.copyFile(this.excelData, fileToCreate);
UploadExcel obj=new UploadExcel();
obj.readExcel(excelData.getAbsolutePath());
}
catch(Exception e){
e.printStackTrace();
addActionError(e.getMessage());
return INPUT;
}
return SUCCESS;
}
/*
*Method to read the each sheet ,row & column of the excel sheet of the uploaded xls file
*/
public void readExcel(String filePath)
{
try
{
FileInputStream file=new FileInputStream(new File(filePath));
//Getting the instance for XLS file
HSSFWorkbook workbook=new HSSFWorkbook(file);
//Get First sheet from the workbook
HSSFSheet sheet=workbook.getSheetAt(0);
ArrayList myList = new ArrayList();
//Iterate start from the first sheet of the uploaded excel file
Iterator<Row> rowIterator = sheet.iterator();
while(rowIterator.hasNext())
{
Row row=rowIterator.next();
if(row.getRowNum()==0)
{
continue;//skip to read the first row of file
}
//For each row, iterate through each coulumns
Iterator<Cell> cellIterator=row.cellIterator();
while(cellIterator.hasNext())
{
Cell cell=cellIterator.next();
if(cell.getColumnIndex()==0)
{
continue;
}
switch(cell.getCellType())
{
case Cell.CELL_TYPE_BOOLEAN:
System.out.print(cell.getBooleanCellValue() + "\t\t");
// myList.add(cell.getBooleanCellValue());
break;
case Cell.CELL_TYPE_NUMERIC:
System.out.print(cell.getNumericCellValue()+ "\t\t");
// myList.add(cell.getNumericCellValue());
break;
case Cell.CELL_TYPE_STRING:
System.out.print(cell.getStringCellValue()+ "\t\t");
// myList.add(cell.getStringCellValue());
break;
}
}
System.out.println("");
}
file.close();
FileOutputStream out=
new FileOutputStream(new File(filePath));
workbook.write(out);
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
In console output:
TEXTit 6695 PROSPECT RD Nova Scotia B3z 3t1
row2sdfsda 61695 P sfsdfdsf 23B3z 3t1
What i thought is,
I have to get the row one by one and i will add this row data to my POJO class object and send it to dao , and finally use saveOrupdate(tableobj)
of hibernate method to save the data into my db table.
But i could not able to think, how can i add these data to my Pojo class?
Hope someone can help me here.