我能够从下面的代码中读取 excel 文件数据,但是在读取 excel 文件后,我无法获取如何获取 Excel 数据以便存储在 POJO 类中的逻辑。
简而言之:我很困惑如何将这些读取的 Excel 数据发送到我的模型类以存储在我的数据库表中?
以下代码在我的 Eclipse 控制台中正确打印 excel 行:
..............
..............
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 columns
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();
}
}
}
在控制台输出中:
TEXTit 6695 PROSPECT RD Nova Scotia B3z 3t1
row2sdfsda 61695 P sfsdfdsf 23B3z 3t1
我的想法是:我必须逐行获取,然后将此行数据添加到我的 POJO 类对象中并将其发送到 dao,最后使用saveOrupdate(tableobj)
hibernate 方法将数据保存到我的 db 表中。
但我无法想到如何将这些数据添加到我的 Pojo 类中。
希望有人可以在这里帮助我。