Java-读取excel文件后如何在db表中插入行

时间:2013-09-11 13:07:58

标签: java excel struts2 apache-poi

我能够从下面的代码中读取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 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();
            }

        }




    }

在控制台输出中:

TEXTit      6695 PROSPECT RD        Nova Scotia     B3z 3t1 

row2sdfsda      61695 P         sfsdfdsf        23B3z 3t1   

我的想法是, 我必须逐行获取行,我将把这个行数据添加到我的POJO类对象并将其发送到dao,最后使用saveOrupdate(tableobj)的hibernate方法将数据保存到我的db表中。 但我无法思考,我怎样才能将这些数据添加到我的Pojo类中?

希望有人可以帮助我。

2 个答案:

答案 0 :(得分:1)

您可以将DAO的引用注入/传递给UploadExcel类。然后在readExcel()方法中,您可以创建新的ENTITY并用值填充它。

                  Entity entity = new Entity();


                  while(cellIterator.hasNext())
                  {
                      Cell cell=cellIterator.next();
                      if(cell.getColumnIndex()==0)
                      {
                          continue;
                      }
                      switch(cell.getCellType())
                      {
                         case Cell.CELL_TYPE_BOOLEAN:
                              entity.setBooleanValue(cell.getBooleanValue);
                              break;
                         ...
                      }

                  }   

最后,您通过DAO插入/ createOrUpdate您的实体。

                  dao.insertOrUpdate(entity);

*编辑* 用于解释评论的代码

实体只是自定义实体的一个示例,它对从excel读取的数据进行建模。 例如,如果您的Excel包含有关客户的数据,那么您可以创建 客户实体。

public class Customer {

    private String name;
    private String surname;
    private Integer age;

    public void setName(String name) {
        this.name = name;
    }

    public String getName() {
       return name;
    }

    // + getters and setters for other fields
}    

然后将填充了excel数据的实体发送到您的DAO(管理客户表),并将给定的实体插入数据库。

* EDIT2 *

删除“dao.saveOrUpdateCompany(company);”来自以下代码:

    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;
    }

你想要一个新的实体PER ROW,现在你只需要在类的开头创建一个实体

阅读代码

后面的评论
    public void readExcel(String filePath)
    { 
        try
         {
             List sheetData = new ArrayList();
            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);

            //Iterate start from the first sheet of the uploaded excel file
              Iterator<Row> rowIterator = sheet.iterator();

              while (rowIterator.hasNext()) {
                   Row row = (Row) rowIterator.next();

                   // CHANGE 
                   Company company = new Company();
                   company.setName(getCellValue(row.getCell((short)1)));

                   // HERE YOU CAN SAVE COMPANY 
                   dao.saveOrUpdateCompany(company);

                   // OR ADD COMPANY TO LIST 
                   // List<Company> companies = new ArrayList<Company>();
                   // Declare just one list for entire class not per row
                   // In this case you call custom made DAO method which batch save
                   // all company entities in list but you call this custom method
                   // at the end of excel processing (your original dao code position).
                   // Try it without list first  
                   list.add(company);    


              }



              System.out.println("Seet data size-"+sheetData.size());
              file.close();
            FileOutputStream out=
                    new FileOutputStream(new File(filePath));

              workbook.write(out);
              out.close();


        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

* EDIT3 *

我认为这最终应该有效

       try{
            session=HibernateUtil.getSessionFactory().openSession();
            transaction=session.beginTransaction();
            for(int i=0;i<companies.size();i++)
            {   
                // THIS IS BAD 
                //Company com=new Company();
                //You need this
                Company com = companies.get(i);
                session.saveOrUpdate(com);
            }
            transaction.commit();
            status++;

        }

答案 1 :(得分:0)

     Iterator iterator = workSheet.rowIterator();
          while (iterator.hasNext()) {
         Row row = (Row) iterator.next();
// check each cell for null and by using getCellValue() method. and inject the value in to user defined pojo.
    }


 private String getCellValue(Cell cell) {
        if (cell == null) {
            return null;
        }
        if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
            return cell.getStringCellValue();
        } else if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
            return cell.getNumericCellValue() + "";
        } else if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
            return cell.getBooleanCellValue() + "";
        }else if(cell.getCellType() == Cell.CELL_TYPE_BLANK){
            return cell.getStringCellValue();
        }else if(cell.getCellType() == Cell.CELL_TYPE_ERROR){
            return cell.getErrorCellValue() + "";
        } 
        else {
            return null;
        }
    }