【发布时间】:2013-09-11 13:07:57
【问题描述】:
我可以从下面的代码中读取 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方法将数据保存到我的数据库表。
但我无法想到如何将这些数据添加到我的 Pojo 类中。
希望有人可以在这里帮助我。
【问题讨论】:
-
不要将每一行一个一个地发送到您的 DAO。这将是可怕的缓慢..您可以传入您的对象类型的列表,并通过批量插入在 1 个干净的事务中执行此操作
-
@steelshark 您能否按照您的建议发布答案。我正在学习 struts2 hibernate,我无法理解您在此评论中所说的内容。
-
@steelshark 我在这里写了代码click here,正如你在评论中所建议的那样,但它没有插入我的数据库,也没有显示任何错误
标签: java excel struts2 apache-poi