java - Servlet 只读取 Excel 文件的前两行

标签 java mysql excel servlets apache-poi

我是一名 Java 初学者,尝试使用 Apache POI 上传 .xls 文件。该文件正在完全上传,但不幸的是只有前两行被插入到数据库中,我想要所有的行。我调试了代码,发现从第二行开始的数据解析完成后抛出错误:java.lang.IllegalStateException: Cannot forward after response has been committed

package com;
public class FileUploadServlet extends HttpServlet {

private static final long serialVersionUID = 1L;
private static final String UPLOAD_DIRECTORY = "upload";
private static final int THRESHOLD_SIZE     = 1024 * 1024 * 3;  // 3MB
private static final int MAX_FILE_SIZE      = 1024 * 1024 * 40; // 40MB
private static final int MAX_REQUEST_SIZE   = 1024 * 1024 * 50; // 50MB


protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    // checks if the request actually contains upload file
    if (!ServletFileUpload.isMultipartContent(request)) {
        PrintWriter writer = response.getWriter();
        writer.println("Request does not contain upload data");
        writer.flush();
        return;
    }

    // configures upload settings
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(THRESHOLD_SIZE);
    factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setFileSizeMax(MAX_FILE_SIZE);
    upload.setSizeMax(MAX_REQUEST_SIZE);

    // constructs the directory path to store upload file
    String uploadPath = getServletContext().getRealPath("")
        + File.separator + UPLOAD_DIRECTORY;
    // creates the directory if it does not exist
    File uploadDir = new File(uploadPath);
    if (!uploadDir.exists()) {
        uploadDir.mkdir();
    }

    try {
        // parses the request's content to extract file data
        List formItems = upload.parseRequest(request);
        Iterator iter = formItems.iterator();

        // iterates over form's fields
        while (iter.hasNext()) {
            FileItem item = (FileItem)iter.next();
            // processes only fields that are not form fields
            if (!item.isFormField()) {
                String fileName = new File(item.getName()).getName();
                String filePath = uploadPath + File.separator + fileName;

                File storeFile = new File(filePath);
                System.out.println("Uploaded at " + filePath);
                // saves the file on disk
                item.write(storeFile);


                File file = new File(filePath);
                InputStream input = new BufferedInputStream(new FileInputStream(file));
                POIFSFileSystem fs = new POIFSFileSystem(input);
                HSSFWorkbook wb = new HSSFWorkbook(fs);
                HSSFSheet sheet = wb.getSheetAt(0);
                //int i = 0;
                Iterator rows = sheet.rowIterator();
                while (rows.hasNext()) {
                    List list = new ArrayList();

                    HSSFRow row = (HSSFRow)rows.next();
                    System.out.println("\n");
                    Iterator cells = row.cellIterator();

                    while (cells.hasNext()) {
                        HSSFCell cell = (HSSFCell)cells.next();
                        if (HSSFCell.CELL_TYPE_NUMERIC == cell.getCellType()) {
                            System.out.print(cell.getNumericCellValue() + " ");
                            list.add(cell.getNumericCellValue());
                        } else if (HSSFCell.CELL_TYPE_STRING == cell.getCellType()) {
                            System.out.print(cell.getStringCellValue() + " ");
                            list.add(cell.getStringCellValue());
                        } else if (HSSFCell.CELL_TYPE_BOOLEAN == cell.getCellType()) {
                            System.out.print(cell.getBooleanCellValue() + " ");
                            list.add(cell.getBooleanCellValue());
                        } else if (HSSFCell.CELL_TYPE_BLANK == cell.getCellType()) {
                            System.out.print("BLANK     ");
                        } else
                            System.out.print("Unknown cell type");
                    }
                    insertRowInDB(request,response,list);
                }
            }
        }
    } catch (Exception ex) {
        request.setAttribute("message", "There was an error: " + ex.getMessage());
    }
}
public void insertRowInDB(HttpServletRequest request, HttpServletResponse response, List cellValues) throws ServletException, IOException {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    Connection con = null;
    PreparedStatement psmt = null;

    try {
        Class.forName("com.mysql.jdbc.Driver");

        psmt = (PreparedStatement)con.prepareStatement("INSERT INTO lillyTT" + " VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
        int paramIndex = 1;
        for (Object cell : cellValues) {
            psmt.setObject(paramIndex, cell);
            paramIndex++;
        }
        int status = psmt.executeUpdate();

        if (status > 0) {
            System.out.println("successful");
            RequestDispatcher rd = request.getRequestDispatcher("SelectOption.jsp");
            rd.forward(request, response);
        }
    } catch(SQLException ex) {
        ex.printStackTrace();
        /* log the exception */
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } finally {
        try {
            out.close();
            psmt.close();
            con.close();
        } catch(SQLException ignored) {
        }
    }
}

}

最佳答案

那是因为每次你调用insertRowInDB()时,该方法都是使用PrintWriter写一个响应,你只能发送一个响应一次。尝试将其删除。

关于java - Servlet 只读取 Excel 文件的前两行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25184134/

相关文章:

Java多线程: why is execution not stopping at join()?

java - 如何通过该 API 代码发送邮件?

mysql - 如何在一张表中保存多种不同的数据类型

vba - 添加水平轴标签 - VBA Excel

java - Apache POI 有效删除多列

java - Selenium 中的数据提供者与 TestNG 不匹配

java - QueryDSL 使用 native SQL 连接和子查询

java - 如何忽略附加在单词上的标点符号和符号,以便在考虑字数统计时将它们全部视为相同?

mysql - 如何通过两个 IN 变量进行排序

php - Mysql MATCH AGAINST空字段给出所有结果