读书人

急大侠救命!java POI 处置excel 取数

发布时间: 2012-09-18 16:21:42 作者: rapoo

急急!大侠救命!java POI 处理excel 取数据报错 。
excel 数据格式如下:
姓名*学号*省份证号* 城市 卡号 人品值
------------------------------------------
李爱你43QW12121221 1 1 好的
java代码:

Java code
    sheet.getCellComment(0, i) ;    Row row = (Row) sheet.getRow(i);    StudentDto student = new StudentDto();    //获取用户信息    String name = row.getCell(0).getRichStringCellValue().toString();//姓名    String code = row.getCell(1).getRichStringCellValue().toString();//学号    String idCard = row.getCell(2).getRichStringCellValue().toString();//身份证    String instidute = row.getCell(3).getRichStringCellValue().toString();//城市    String major = row.getCell(4).getRichStringCellValue().toString();//卡号    String state = row.getCell(5).getRichStringCellValue().toString();//人品值

如上内容出现这样的情况:
当我取excle 姓名 和 学号都是OK 的 。 但是 当我取 城市 和卡号 的时候都会报错 。
我把 城市 和 卡号 改成: 1a 和 1b 的时候 又不会报错 。说到底 就是 去excle里面的整形 数据就会报错。为什么。大侠 救命 小弟分全给你。


[解决办法]
报的什么异常内容?断点一步步调试看看,
row.getCell(3).getRichStringCellValue().toString();//城市
把toString()去掉看看。

[解决办法]
类似这样做个判断。获取数居前,先要知道cell的类型
Java code
HSSFCell c = row.getCell(8);if (c.getCellType() == HSSFCell.CELL_TYPE_STRING) {  String s = row.getCell(8).getRichStringCellValue().getString();  if (NumberUtils.isNumber(s)) {    return new Double(s);  } else {    return 0.0;  }} else {  return row.getCell(8).getNumericCellValue();}
[解决办法]
取单元格内数据时,先判断一下数据类型即可。


Java code
Sheet sheet1 = wb.getSheetAt(0);    for (Row row : sheet1) {        for (Cell cell : row) {            CellReference cellRef = new CellReference(row.getRowNum(), cell.getColumnIndex());            System.out.print(cellRef.formatAsString());            System.out.print(" - ");            switch (cell.getCellType()) {                case Cell.CELL_TYPE_STRING:                    System.out.println(cell.getRichStringCellValue().getString());                    break;                case Cell.CELL_TYPE_NUMERIC:                    if (DateUtil.isCellDateFormatted(cell)) {                        System.out.println(cell.getDateCellValue());                    } else {                        System.out.println(cell.getNumericCellValue());                    }                    break;                case Cell.CELL_TYPE_BOOLEAN:                    System.out.println(cell.getBooleanCellValue());                    break;                case Cell.CELL_TYPE_FORMULA:                    System.out.println(cell.getCellFormula());                    break;                default:                    System.out.println();            }        }    }
[解决办法]
取得cell值时要判断类型。
getCellType() ==

CELL_TYPE_BLANK
空值

CELL_TYPE_BOOLEAN
布尔型

CELL_TYPE_ERROR
错误

CELL_TYPE_FORMULA
公式型

CELL_TYPE_STRING
字符串型

CELL_TYPE_NUMERIC
数值型
[解决办法]
最简单的方法
String cellStr=row.getCell(8).toString();
我导入excle到数据库里的思路是:
1.选择excle文件
2.上传到服务器
3.读excle文件,返回一个String[][]
4.数组当参数,传入数据库插入的方法里

如果数据库类型是int 那就在去数组值的时候 转换一下

读书人网 >J2EE开发

热点推荐