Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/362.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何读取excel多张工作表以将excel工作表的内容存储到数据库中_Java_Excel_Jdbc - Fatal编程技术网

Java 如何读取excel多张工作表以将excel工作表的内容存储到数据库中

Java 如何读取excel多张工作表以将excel工作表的内容存储到数据库中,java,excel,jdbc,Java,Excel,Jdbc,我是java新手, 现在,我已经创建了用于读取excel工作表并使用ApachePOI将其发送到数据库的代码。 我已经通过第一次查询成功地阅读了第1页,并将其发送到数据库,但我不知道如何通过第二次查询和表格阅读第2页。 这两张表有两个不同的问题,如何在准备的陈述中提及。 或者有没有其他方法可以做到这一点。 请帮我解决这个问题。 代码是 <html> <head> <meta http-equiv="Content-Type" content="text/html"&

我是java新手, 现在,我已经创建了用于读取excel工作表并使用ApachePOI将其发送到数据库的代码。 我已经通过第一次查询成功地阅读了第1页,并将其发送到数据库,但我不知道如何通过第二次查询和表格阅读第2页。 这两张表有两个不同的问题,如何在准备的陈述中提及。 或者有没有其他方法可以做到这一点。 请帮我解决这个问题。 代码是

<html>
<head>
<meta http-equiv="Content-Type" content="text/html">
<title>Excel</title>
</head>
<body>
<FORM ENCTYPE="multipart/form-data" ACTION="Excel.jsp" METHOD=POST>
<br><br><br>
<center><table border="2" >
<tr><center><td colspan="2"><p align="center"><B>UPLOAD THE FILE</B><center></td></tr>
<tr><td><b>Choose the file To Upload:</b>
</td>
 <td><INPUT NAME="file" TYPE="file" accept=".csv, application/vnd.openxmlformats-  officedocument.spreadsheetml.sheet, application/vnd.ms-excel"></td></tr>
 <tr><td colspan="2">
 <p align="right"><INPUT TYPE="submit" VALUE="Send File" ></p></td></tr>
 </center>
 </FORM>
  </body>

 <jsp:useBean id="connection" class="DB.DB_Connection" scope="page">
 <jsp:setProperty name="connection" property="*"/>
 </jsp:useBean> 
  </html>

 <%!     
   Connection con;
   PreparedStatement ps=null;
   PreparedStatement ps2=null;
   public static ArrayList readExcelFile(String fileName) throws SQLException
   {
     /** --Define a ArrayList
      --Holds ArrayList Of Cells

      */

      ArrayList cellArrayLisstHolder = new ArrayList();

     try{
           /** Creating Input Stream**/
          FileInputStream myInput = new FileInputStream(fileName);

          /** Create a POIFSFileSystem object**/
           POIFSFileSystem myFileSystem = new POIFSFileSystem(myInput);

          /** Create a workbook using the File System**/
           HSSFWorkbook myWorkBook = new HSSFWorkbook(myFileSystem);

          /** Get the first sheet from workbook**/

            HSSFSheet mySheet = myWorkBook.getSheetAt(0);
            HSSFSheet mySheet2 = myWorkBook.getSheetAt(1);


         /** We now need something to iterate through the cells.**/
            Iterator rowIter = mySheet.rowIterator();
            Iterator rowIter1 = mySheet2.rowIterator();
             while(rowIter.hasNext()){
             HSSFRow myRow = (HSSFRow) rowIter.next();
             Iterator cellIter = myRow.cellIterator();
              ArrayList cellStoreArrayList=new ArrayList();

             while(cellIter.hasNext()){
             HSSFCell myCell = (HSSFCell) cellIter.next();

              HSSFCell cell;

          short i= 1;

          do {
              cell = myRow.getCell(i);// Start from first column

              if (cell == null) {
                 break;
              }
              if (cell.getCellType() == HSSFCell.CELL_TYPE_STRING) {
                 // Plain String Cell.
                 System.out.println("The Cell is a String with value : "
                       + cell.getStringCellValue());
              } else if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {

                 // Excel stores the Date as a Numeric Contents. POI provides
                 // a Date utility to check
                 // if a particular cell is formatted as a date.
                 if (HSSFDateUtil.isCellDateFormatted(cell)) {

                    Date date = HSSFDateUtil.getJavaDate((double) cell
                          .getNumericCellValue());

                    SimpleDateFormat df = new SimpleDateFormat("dd/mm/yyyy");
                    System.out.println("The cell is a Date : " + df.format(date));
                 } else {
                    // treat the cell as 'double' number
                    System.out.println("The cell is a number : "
                          + cell.getNumericCellValue());
                 }

              } else if (cell.getCellType() == HSSFCell.CELL_TYPE_BLANK) {
                 // Some of the cells will be rendered blank when cells in
                 // Excel are merged... one such cell
                 System.out
                 .println("A Blank Cell Encountered.... any merging happened???");
              } else {
                 System.out.println("The cell is nothing we're interested in ...");
              }
              i++; // increment cell counter!!!
           } while (cell != null);

          cellStoreArrayList.add(myCell);

                    }
      cellArrayLisstHolder.add(cellStoreArrayList);
  }
  while(rowIter1.hasNext()){
      HSSFRow myRow1 = (HSSFRow) rowIter.next();
      Iterator cellIter1 = myRow1.cellIterator();
      ArrayList cellStoreArrayList1=new ArrayList();
      while(cellIter1.hasNext()){
          HSSFCell myCell1 = (HSSFCell) cellIter1.next();
          HSSFCell cell1;
          short i= 1;
          do {
              cell1 = myRow1.getCell(i); // Start from first column
              if (cell1 == null) {
                 break;
              }
              if (cell1.getCellType() == HSSFCell.CELL_TYPE_STRING) {
                 // Plain String Cell.
                 System.out.println("The Cell is a String with value : "
                       + cell1.getStringCellValue());
              } else if (cell1.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {

                 // Excel stores the Date as a Numeric Contents. POI provides
                 // a Date utility to check
                 // if a particular cell is formatted as a date.
                 if (HSSFDateUtil.isCellDateFormatted(cell1)) {
                    Date date = HSSFDateUtil.getJavaDate((double) cell1
                          .getNumericCellValue());
                    SimpleDateFormat df = new SimpleDateFormat("mm/dd/yyyy");
                    System.out.println("The cell is a Date : " + df.format(date));
                 } else {
                    // treat the cell as 'double' number
                    System.out.println("The cell is a number : "
                          + cell1.getNumericCellValue());
                 }

              } else if (cell1.getCellType() == HSSFCell.CELL_TYPE_BLANK) {
                 // Some of the cells will be rendered blank when cells in
                 // Excel are merged... one such cell
                 System.out
                 .println("A Blank Cell Encountered.... any merging happened???");
              } else {
                 System.out.println("The cell is nothing we're interested in ...");
              }
              i++; // increment cell counter!!!
           } while (cell1 != null);

          cellStoreArrayList1.add(myCell1);

                    }
      cellArrayLisstHolder.add(cellStoreArrayList1);
  }
}catch (Exception e){e.printStackTrace(); }
return cellArrayLisstHolder;
}


%>
<%

 File f = new File("DeptHosp.xls");
   System.out.println(f.getAbsolutePath());

  File file = new File("."); 
 for(String fileNames : file.list()) System.out.println(fileNames);
String fileName="D://PROJECT//SOFTWARES//eclipse_Juno//eclipse//DeptHosp.xls";             
System.out.println(" path found");
ArrayList dataHolder=readExcelFile(fileName);
//Print the data read
//printCellDataToConsole(dataHolder);

con=connection.getConn();
 System.out.println("Inserting the details");
 String query="insert into   departmentmaster(Dept_id,Dept_Groupid,Dept_Kid,Dept_Groupkid,Dept_Group,Dept_Name,Dept_type,Dept_HospitalId,Dept_datecreated,Dept_datelastrefreshed)values(?,?,?,?,?,?,?,?,?,?)";
  String query1="insert into hospitalmaster(hospital_group,hospital_name)values(?,?)";
   ps=con.prepareStatement(query);
  ps2=con.prepareStatement(query1);
   System.out.println("Database");
  int count=0;
     ArrayList cellStoreArrayList=null;
    Date datevalue=null;

  //For inserting into database
    for (int i=1;i < dataHolder.size(); i++) {
    cellStoreArrayList=(ArrayList)dataHolder.get(i);


   ps.setString(1,((HSSFCell)cellStoreArrayList.get(1)).getStringCellValue());
   ps.setString(2,((HSSFCell)cellStoreArrayList.get(1)).getStringCellValue());
   ps.setString(3,((HSSFCell)cellStoreArrayList.get(2)).getStringCellValue());
   ps.setString(4,((HSSFCell)cellStoreArrayList.get(3)).getStringCellValue());
   ps.setString(5,((HSSFCell)cellStoreArrayList.get(4)).getStringCellValue());
   ps.setString(6,((HSSFCell)cellStoreArrayList.get(5)).getStringCellValue());
   ps.setString(7,((HSSFCell)cellStoreArrayList.get(6)).getStringCellValue());
   ps.setString(8,((HSSFCell)cellStoreArrayList.get(7)).getStringCellValue());
   ps.setString(9,((HSSFCell)cellStoreArrayList.get(8)).getStringCellValue());
   ps.setString(10,((HSSFCell)cellStoreArrayList.get(9)).getStringCellValue());
   count= ps.executeUpdate();
   ps2.setString(1,((HSSFCell)cellStoreArrayList.get(1)).getStringCellValue());
   ps2.setString(2,((HSSFCell)cellStoreArrayList.get(1)).getStringCellValue());
   count= ps2.executeUpdate();

   }

 </body>
</html>

擅长



上传文件 选择要上载的文件:


也许你把东西混在一起了。您已经解决了如何显示JSP、读取带有POI的Excel文件以及将行写入数据库的问题。我建议您重新设计代码以分离这些任务。可能是一个简单的类(Reader.java),它只读取excel文件并为每张工作表生成一个
ArrayList
,然后是一个简单的类(Writer.java),包含两个方法,每个方法都获取一个
ArrayList
,并根据需要将它们写入数据库。这将导致一个更简单的自顶向下的设计,这将更容易调试

顺便说一下,您正在代码中创建一个数据库连接,而不是返回它。您应该为应用程序中使用的每个数据库资源(
ResultSets
语句
连接
)调用
.close()
方法,或者使用一些惯用法(尝试使用资源、Spring资源管理等)确保这样做

附加内容:当您对java感到更满意时,可以看看

这是连接到web应用程序中可能有数百或数千个并发用户的数据库的首选方式。你的想法是,为每一次访问你的页面打开一个新的连接,这对于学术活动来说是完全正确的,这将在实际环境中导致效率问题。也许你的应用服务器有一个内置的连接池机制(最新版本的Tomcat,WebLogic,WebSphere中有它们),或者你可以考虑使用Apache DCP或C3PO。< /P>可能的副本