0

在我的项目中,我有一个 excel 表,其中包含大量的标记、id、学分……我需要从 excel 文件上传到数据库中……我正在使用 apache poi 读取和更新,但我遇到了错误……

DB_Connection.java

      package DB;
      import java.sql.*;
      import java.sql.Connection;
      import java.sql.DriverManager;
      import java.sql.SQLException;
      public class DB_Connection 
      {
                // private String datasize;
                    private Connection con;
                 public DB_Connection()
                 {


                     try
                {
                            String conUrl="jdbc:oracle:thin:@localhost:1521:xe";
                           String userName="SYSTEM";
                            String pass="raje";
                           Class.forName("oracle.jdbc.driver.OracleDriver");
                               con=DriverManager.getConnection(conUrl,userName,pass);
                }
                catch(Exception s)
                {
                       System.out.println(s);
                }


             }
          public Connection getConn()
            {
               return con;
            }
         public void setConn(Connection con)
          {
                 this.con = con;
          }

        }

读取Excel.jsp:

      <%@page  language="java" import="java.sql.*"  contentType="text/html"   pageEncoding="UTF-8" %>
      <!DOCTYPE html>

       <%@ page import ="java.util.Date" %>
       <%@ page import ="java.io.*" %>
       <%@ page import ="java.io.FileNotFoundException" %>
       <%@ page import ="java.io.IOException" %>
       <%@ page import ="java.util.Iterator" %>
       <%@ page import ="java.util.ArrayList" %>
       <%@ page import ="org.apache.poi.hssf.usermodel.HSSFCell" %>
       <%@ page import ="org.apache.poi.hssf.usermodel.HSSFRow" %>
       <%@ page import ="org.apache.poi.hssf.usermodel.HSSFSheet" %>
       <%@ page import ="org.apache.poi.hssf.usermodel.HSSFWorkbook" %>
       <%@ page import ="org.apache.poi.poifs.filesystem.POIFSFileSystem" %>
   <html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>

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

       </jsp:useBean> 

        <%!     
           Connection con;
           PreparedStatement ps=null;

         public static ArrayList readExcelFile(String fileName)
          {
    /** --Define a ArrayList
        --Holds ArrayList Of Cells
     */

    ArrayList cellArrayListHolder = new ArrayList();

    try{
    /** Creating Input Stream**/
        FileInputStream myInput = new FileInputStream(fileName);
       // System.out.print("myInput");


    /** 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);

    /** We now need something to iterate through the cells.**/
      Iterator rowIter = mySheet.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();                   
              cellStoreArrayList.add(myCell);
          }

          cellArrayListHolder.add(cellStoreArrayList);
      }

    }
    catch (Exception e)
    {

        e.printStackTrace(); 
    }
    return cellArrayListHolder;

       }%>


     <%
        String fileName="C://Documents and Settings//raje//Desktop//JGRESULTS1.xls"; 
            ArrayList dataHolder=readExcelFile(fileName);
        //Print the data read
       //printCellDataToConsole(dataHolder);
         con= connection.getConn();
          ps=con.prepareStatement("insert into sample2 values(?,?,?,?)");
              int count=1;
         ArrayList cellStoreArrayList=null;
        //For inserting into database
         for (int i=1;i < dataHolder.size(); i++)
          {
              cellStoreArrayList=(ArrayList)dataHolder.get(i);
       ps.setString(1,((HSSFCell)cellStoreArrayList.get(0)).toString());
       ps.setString(2,((HSSFCell)cellStoreArrayList.get(1)).toString());
       ps.setString(3,((HSSFCell)cellStoreArrayList.get(2)).toString());
       ps.setString(4,((HSSFCell)cellStoreArrayList.get(3)).toString()); 
      count= ps.executeUpdate();
       System.out.print(((HSSFCell)cellStoreArrayList.get(3)).toString() + "\t");
       }
               count++;
         //For checking data is inserted or not?
           if(count>0)
        { %>
               Following details from Excel file have been inserted in student table of database
                   <table>
                       <tr>
                           <th>Student's Name</th>
                           <th>Class</th>
                           <th>external</th>
                           <th>credits</th>
                       </tr>

        <% for (int i=1;i < dataHolder.size(); i++) {
              cell StoreArrayList=(ArrayList)dataHolder.get(i);%>
           <tr>
        <td><%=((HSSFCell)cellStoreArrayList.get(0)).toString() %></td>
        <td><%=((HSSFCell)cellStoreArrayList.get(1)).toString() %></td>
        <td><%=((HSSFCell)cellStoreArrayList.get(2)).toString() %></td>
        <td><%=((HSSFCell)cellStoreArrayList.get(3)).toString() %></td>

            </tr>
       <%}
      }
              else
               {%>

             <%  out.print("not successfull"); 
             }    %> 
       </table>

</body>
</html>

输出:

类型异常报告

信息

描述 服务器遇到一个内部错误 () 阻止它完成这个请求。

例外

org.apache.jasper.JasperException: An exception occurred processing JSP page /readExcel.jsp at line 98

95:     {
96:     cellStoreArrayList=(ArrayList)dataHolder.get(i);
97:        ps.setString(1,((HSSFCell)cellStoreArrayList.get(0)).toString());
98:        ps.setString(2,((HSSFCell)cellStoreArrayList.get(1)).toString());
99:        ps.setString(3,((HSSFCell)cellStoreArrayList.get(2)).toString());
100:        ps.setString(4,((HSSFCell)cellStoreArrayList.get(3)).toString()); 
101:       count= ps.executeUpdate();

堆栈跟踪:

    org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:553)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:457)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:333)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
    org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:3 93)
    root cause

         java.lang.IndexOutOfBoundsException: Index: 1, Size: 1
    java.util.ArrayList.RangeCheck(ArrayList.java:547)
    java.util.ArrayList.get(ArrayList.java:322)
    org.apache.jsp.readExcel_jsp._jspService(readExcel_jsp.java:175)
    org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:419)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:333)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
    org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
4

3 回答 3

1

如果您实际发布错误,您将获得更多更好的帮助。

这段代码很乱。它做的太多了:

  1. POI 读取和解析电子表格
  2. 显示的 JSP
  3. JDBC 持久化

我建议将其分解为可以开发、测试和搁置的单独类。

没有人应该使用 scriptlet 编写 JSP。那是一种名誉扫地的 1999 年风格。最好学习 JSTL 并添加一些 servlet。

更新:

原因如下:

java.lang.IndexOutOfBoundsException: Index: 1, Size: 1
    java.util.ArrayList.RangeCheck(ArrayList.java:547)

您假设存在一个数组元素,但 JVM 不同意您的看法。

这是你做错的本质:

List<String> values = new ArrayList<String>();
values.add("element one"); 
System.out.println(values.size());  // this will print 1
System.out.println(values.get(100)); // there's only one element in the list, but you tried to access 100.  

错误!找出你的代码在哪里做了这样的事情,你就会得到它。

于 2013-02-20T14:22:03.573 回答
0

正如有人指出的那样:你所做的是一种非常糟糕的做法......

但是,当前的问题很可能是您尝试从中读取单元格的行不够长,因此(注意:array backed)列表超出范围。

为了为这种情况做好准备,我会这样做:

   cellStoreArrayList=(ArrayList)dataHolder.get(i);
   for(int i=1;i<4;i++) { // I'd use a loop even for fixed number of iterations, I vigorously hate duplication
       if(cellStoreArrayList.size()>=i) { // check for row to be long enough --> no ArrayOutOfBounds anymore               HSSFCell cell = (HSSFCell)cellStoreArrayList.get(i-1);
           if(cell!=null) { // check for null: no NullPointerException anymore...
               ps.setString(i,cell.toString());
           }
           else {
               ps.setString(i,"");
           }
           //ps.setString(i,cell==null?"":cell.toString()); //this is good too, but a bit probably less readable
       }
   }

备注

  • 使用泛型!List 可以有一个 <HSSFCell>通用类型,消除了强制转换的需要,并解决了相当多的错误和错误可能性
  • 不要将实现的名称存储在变量名中!cellStoreArrayList= 糟糕!cellStoreList= 好
于 2013-02-20T14:28:12.327 回答
0

从查看您的代码和堆栈跟踪来看,您似乎得到了一个,IndexOutOfBoundsException因为其中的单元格行的cellStoreArrayList长度仅为 1。我建议您查看您的电子表格,以确保您正在读取的每一行都有 4 列,因为约束是硬编码的。

在相关的说明中,如果您要对数组索引进行硬编码,您应该将其包围在某种异常捕获机制中。

于 2013-02-20T14:30:48.227 回答