POI阅读脱颖而出的字符串作为数字 [英] POI reading excel strings as numeric

查看:121
本文介绍了POI阅读脱颖而出的字符串作为数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Apache POI读取Excel文件。虽然看完我已经注意到,它需要字符串作为浮点值。

如果我的单元格包含1,那么它会读取它为1.0

我从previous问题,一些提示这里并修改了code,但仍浮重presentation保持原样。

我将如何读正确的字符串和日期的数据?

  DataFormatter DF =新DataFormatter();        对于(鳞次栉比:表){            对(INT CN = 0; CN&下; row.getLastCellNum(); CN ++){
                   //如果该单元被从文件丢失,产生一个空白的
                   //(通过指定M​​issingCellPolicy厂)
                   电池单元= row.getCell(CN,Row.CREATE_NULL_AS_BLANK);
                   //打印调试单元
                   cell.setCellType(Cell.CELL_TYPE_STRING);                   的System.out.println(CELL:+ CN + - >中+ df.formatCellValue(单元));                   如果(row.getRowNum()== 0){                        sheetColumnNames.add(cell.getRichStringCellValue()的getString());
                    }            }        }


解决方案

推动评论一个答案

问题是通话

  cell.setCellType(Cell.CELL_TYPE_STRING);

那是什么做的是要求POI尽量细胞免受转换不管它是目前(如数字)转换为字符串。转换适用于尝试做这是一个相当简单的,这就是为什么你失去的格式

如果你只是想找回包含单元格值,如图Excel中的一个字符串,只需调用 DataFormatter 直接,它会做最好。玩与周围的细胞类型只会混淆的东西,将风险失去格式化

I am using Apache POI for reading excel file. And while reading it I have noticed that it takes strings as float values.

If my cell contains 1 then it will fetch it as 1.0

I took some hints from previous questions here and modified the code but still the float representation remains as it is.

How would I read correctly the data for strings and dates?

DataFormatter df = new DataFormatter();

        for (Row row : sheet) {

            for(int cn=0; cn<row.getLastCellNum(); cn++) {
                   // If the cell is missing from the file, generate a blank one
                   // (Works by specifying a MissingCellPolicy)
                   Cell cell = row.getCell(cn, Row.CREATE_NULL_AS_BLANK);
                   // Print the cell for debugging
                   cell.setCellType(Cell.CELL_TYPE_STRING);

                   System.out.println("CELL: " + cn + " --> " + df.formatCellValue(cell));

                   if (row.getRowNum() == 0) {

                        sheetColumnNames.add(cell.getRichStringCellValue().getString());
                    }

            }

        }

解决方案

Promoting a comment to an answer

The problem is the call

cell.setCellType(Cell.CELL_TYPE_STRING);

What that is doing is asking POI to try to convert the cell from whatever it is currently (eg a number) into a string. The conversion applied to try to do this is a fairly simple one, which is why you're loosing the formatting

If you just want to get back a String that contains the Cell Value as shown in Excel, just call DataFormatter directly, and it'll do its best. Playing around with the Cell Type will only confuse things, and will risk loosing formatting

这篇关于POI阅读脱颖而出的字符串作为数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆