poi简析单元格时,报错解决:
https://blog.csdn.net/fz13768884254/article/details/82767297
其他poi相关文档:
https://blog.csdn.net/fz13768884254/article/details/82706936
https://blog.csdn.net/fz13768884254/article/details/82703959
https://blog.csdn.net/fz13768884254/article/details/82707117
项目中需要导入批量数据,导入时id列单元格格式均设置为文本格式,导入时将单元格格式转换为数字类型,这个导入过程都正常,但是后来发现,导入的同一条数据,excel中的id和数据库中导入的id时不一致的。
具体情况:
获取id值,表格中设置为文本类型。
poi简析后将单元格设置为数字类型:
cell_0.setCellType(Cell.CELL_TYPE_NUMERIC);
刚获取值时:
设置数字类型后,再取值时:
@Override
public void setCellType(int cellType) {
int prevType = getCellType();
if(isPartOfArrayFormulaGroup()){
notifyArrayFormulaChanging();
}
if(prevType == CELL_TYPE_FORMULA && cellType != CELL_TYPE_FORMULA) {
getSheet().getWorkbook().onDeleteFormula(this);
}
switch (cellType) {
case CELL_TYPE_BLANK:
setBlank();
break;
case CELL_TYPE_BOOLEAN:
String newVal = convertCellValueToBoolean() ? TRUE_AS_STRING : FALSE_AS_STRING;
_cell.setT(STCellType.B);
_cell.setV(newVal);
break;
case CELL_TYPE_NUMERIC:
_cell.setT(STCellType.N);
break;
case CELL_TYPE_ERROR:
_cell.setT(STCellType.E);
break;
case CELL_TYPE_STRING:
if(prevType != CELL_TYPE_STRING){
String str = convertCellValueToString();
XSSFRichTextString rt = new XSSFRichTextString(str);
rt.setStylesTableReference(_stylesSource);
int sRef = _sharedStringSource.addEntry(rt.getCTRst());
_cell.setV(Integer.toString(sRef));
}
_cell.setT(STCellType.S);
break;
case CELL_TYPE_FORMULA:
if(!_cell.isSetF()){
CTCellFormula f = CTCellFormula.Factory.newInstance();
f.setStringValue("0");
_cell.setF(f);
if(_cell.isSetT()) _cell.unsetT();
}
break;
default:
throw new IllegalArgumentException("Illegal cell type: " + cellType);
}
if (cellType != CELL_TYPE_FORMULA && _cell.isSetF()) {
_cell.unsetF();
}
}
<xml-fragment r="A5" t="n" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:x14ac="http://schemas.microsoft.com/office/spreadsheetml/2009/9/ac" xmlns:main="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
<main:v>8423</main:v>
</xml-fragment>
类是于,先拿到文本值,在转换时,将文本内容对应一个数字格式的值,k-v形式存储,当获取数字类型时,就是直接拿key,而我们需要的是value的值,因此就会存在问题。
解决方法:文本类型的单元格,也设置为文本类型,当转换为java对象后,再进行类型转换。
//excel中设置为文本类型
Cell cell_0 = row.getCell(0);
//再进行一次单元格设置,设置为文本类型
cell_0.setCellType(Cell.CELL_TYPE_STRING);
Map<String, String> map = Maps.newHashMap();
//在java中将字符串转换为对应的数据类型
map.put("id", Double.valueOf(cell_0.getStringCellValue()).longValue()+"");
这样就可以解决,导入前后因为简析数据类型不一致而导致的数据不一致问题。