简体   繁体   English

java.lang.IllegalStateException:将Excel工作表上传到服务器时,无法从文本单元格异常中获取数值

[英]java.lang.IllegalStateException: Cannot get a numeric value from a text cell Exception while uploading excel sheet to server

I am uploading an Excel file to server Ref : How to upload files to server using JSP/Servlet? 我正在将Excel文件上传到服务器参考: 如何使用JSP / Servlet将文件上传到服务器?

Here is my code which causes error 这是我的代码,导致错误

public static ArrayList<MOPBDMMapping> readExcel(InputStream fileInputStream)
    {

        ArrayList<MOPBDMMapping> mappings = new ArrayList<MOPBDMMapping>();
        try{
        HSSFWorkbook workbook = new HSSFWorkbook(fileInputStream);
        HSSFSheet worksheet = workbook.getSheetAt(0);
        HSSFRow row1 = worksheet.getRow(0);

        int noOfRows = worksheet.getLastRowNum();

        for(int i = 1 ; i <= noOfRows ; i++){
            MOPBDMMapping mapping = new MOPBDMMapping();

            HSSFCell cell1 = row1.getCell(0);
            mapping.setMappingID(cell1.getStringCellValue());   

            HSSFCell cell2 = row1.getCell(1);
            mapping.setMopID(cell2.getStringCellValue());

            HSSFCell cell3 = row1.getCell(2);
            mapping.setMopName(cell3.getStringCellValue());

            HSSFCell cell4 = row1.getCell(3);
            mapping.setBdmID(cell4.getStringCellValue());

            HSSFCell cell5 = row1.getCell(4);
            mapping.setBdmName(cell5.getStringCellValue());

            HSSFCell cell6 = row1.getCell(5);
            mapping.setBranch(cell6.getStringCellValue());

            HSSFCell cell7 = row1.getCell(6);
            mapping.setStartDate(cell7.getDateCellValue());   //Error Line

            HSSFCell cell8 = row1.getCell(7);
            mapping.setEndDate(cell8.getDateCellValue());

            HSSFCell cell9 = row1.getCell(8);
            mapping.setActive(cell9.getStringCellValue());

            mappings.add(mapping);
        }
        System.out.println(mappings.size());
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
        return mappings;
    }
}

This is the exception thrown 这是抛出的异常

java.lang.IllegalStateException: Cannot get a numeric value from a text cell
        org.apache.poi.hssf.usermodel.HSSFCell.typeMismatch(HSSFCell.java:643)
        org.apache.poi.hssf.usermodel.HSSFCell.getNumericCellValue(HSSFCell.java:668)
        org.apache.poi.hssf.usermodel.HSSFCell.getDateCellValue(HSSFCell.java:689)
        com.tcs.rspm.mops.business.ExcelReader.readExcel(ExcelReader.java:52)
        com.tcs.rspm.mop.upload.ExcelUploadController.doPost(ExcelUploadController.java:42)
        javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
        javax.servlet.http.HttpServlet.service(HttpServlet.java:722)

Here is my Servlet code 这是我的Servlet代码

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("In controller..");
        try {
            List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
            for (FileItem item : items) {
                if (item.isFormField()) {
                    // Process regular form field (input type="text|radio|checkbox|etc", select, etc).
                    String fieldname = item.getFieldName();
                    String fieldvalue = item.getString();
                    System.out.println( "Normal Field : " + fieldname + fieldvalue);
                    // ... (do your job here)
                } else {
                    // Process form file field (input type="file").
                    String fieldname = item.getFieldName();
                    String filename = FilenameUtils.getName(item.getName());
                    System.out.println("File field : " + fieldname + filename );
                    InputStream filecontent = item.getInputStream();
                    ExcelReader.readExcel(filecontent);

                }
            }
        } catch (FileUploadException e) {
            throw new ServletException("Cannot parse multipart request.", e);
        }
        System.out.println("Out controller..");
        // ...
    }

What can be a reason ? 可能是什么原因? '08/12/13' is the entry in excel sheet ? '08 / 12/13'是Excel工作表中的条目吗? Any solutions ? 有什么解决办法吗?

According to doc getDateCellValue() 根据文档getDateCellValue()

Get the value of the cell as a date. 获取单元格的值作为日期。 For strings we throw an exception. 对于字符串,我们抛出异常。 For blank cells we return a null. 对于空白单元格,我们返回空值。 Returns: the value of the cell as a date 返回:单元格的值作为日期

So you can check to see which type of cell it is using cell.getCellType(). 因此,您可以使用cell.getCellType()检查一下它是哪种类型的单元格。 And you can get the cell value as String and parse it into a Date object using SimpleDateFormat like this 然后,您可以像这样使用SimpleDateFormat将单元格值获取为String并将其解析为Date对象。

SimpleDateFormat dateFormat = new SimpleDateFormat("dd/mm/yy");
        Date date = dateFormat.parse(yourStringDateHere);

If your cell is formatted as date then you can use http://poi.apache.org/apidocs/org/apache/poi/hssf/usermodel/HSSFDateUtil.html to check if the cell contains a date value then get date form it 如果您的单元格格式设置为日期,则可以使用http://poi.apache.org/apidocs/org/apache/poi/hssf/usermodel/HSSFDateUtil.html检查单元格是否包含日期值,然后从中获取日期

if(HSSFDateUtil.isCellDateFormatted(cell)){
            Date date = HSSFDateUtil.getJavaDate(cell.getNumericCellValue());
        } 

And if the cell is not formatted as date ( which is the case here ) but you know it's format and that it's a valid date.you can use the first method to get a date. 如果单元格未格式化为日期( 此处就是这种情况 ),但您知道它的格式并且它是有效日期,则可以使用第一种方法获取日期。

Excel stores Dates as LONG (Numeric). Excel将日期存储为LONG(数字)。 What you want is a SimpleDateFormat to parse your STRING Date. 您想要的是SimpleDateFormat来解析您的STRING日期​​。

SimpleDateFormat sdf = new SimpleDateFormat("mm/dd/yy");
Date d = sdf.parse(cellValueAsString);

The cell in excel is not set to a Date Format, so even the value is formated as date, excel treats it as a string. excel中的单元格未设置为“日期格式”,因此即使值被格式化为日期,excel也会将其视为字符串。 You need to set the cell as date or read it as string and parse to date. 您需要将单元格设置为日期或将其读取为字符串并解析为日期。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 线程“主”java.lang.IllegalStateException 中的异常:无法从数字单元格中获取文本值 - Exception in thread "main" java.lang.IllegalStateException: Cannot get a text value from a numeric cell java.lang.IllegalStateException:无法从文本单元格获取数值 - java.lang.IllegalStateException: Cannot get a numeric value from a text cell 收到此错误:消息:java.lang.IllegalStateException:无法从数字单元格获取文本值 - Getting this error: Message: java.lang.IllegalStateException: Cannot get a text value from a numeric cell java.lang.IllegalStateException:无法从数字公式单元格获取文本值 - java.lang.IllegalStateException: Cannot get a text value from a numeric formula cell 嵌套异常是java.lang.IllegalStateException:无法将类型[java.lang.String]的值转换为所需类型 - nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type “无法在未密封的实例上执行此操作”java.lang.IllegalStateException异常 - “Cannot perform this action on a not sealed instance” java.lang.IllegalStateException exception 异常:java.lang.IllegalStateException:无法转换 OneToOne 映射的类型值 - Exception :java.lang.IllegalStateException: Cannot convert value of type for OneToOne mapping java - 无法从 STRING 单元格异常中获取 NUMERIC 值 - java - Cannot get a NUMERIC value from a STRING cell Exception 如何解决java.lang.IllegalStateException:服务器处于错误状态异常 - How to solve java.lang.IllegalStateException: server in wrong state Exception 无法启动网络服务器; 嵌套异常是 java.lang.IllegalStateException - Unable to start web server; nested exception is java.lang.IllegalStateException
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM