poi读取Excel文件并进行数据类型转换实例
需要jar包:
poi-3.7.jar、poi-examples-3.7.jar、poi-ooxml-3.7.jar、poi-ooxml-schemas-3.7.jar、poi-scratchpad-3.7.jar
action代码:
public String poiImportBusinessExcel(){
List<CaAvApply> caAvApplies = new ArrayList<CaAvApply>();
InputStream input = FileUtils.openInputStream(importFileExcel);
POIFSFileSystem fs = new POIFSFileSystem(input);
HSSFWorkbook wb = new HSSFWorkbook(fs);
HSSFSheet sheet = wb.getSheetAt(0);
Iterator rows = sheet.rowIterator();
while(rows.hasNext()){
HSSFRow row = (HSSFRow) rows.next();
for(int i=0; i<caAvApplies.size(); i++){
HSSFCell cell_1 = row.getCell(1);
if(null != cell_1){
aAvApplies.get(i).setName(changeCellToString(cell_1));
(......其他行照此......)
}
}
}
}
(try catch略去了)
这里HSSFCell 有几种数据类型,如果想进行类型转换,再加一个方法进行转换,这里给的例子是都转换成String类型的数据
public String changeCellToString(HSSFCell cell){
String returnValue = "";
if(null != cell){
switch(cell.getCellType()){
case HSSFCell.CELL_TYPE_NUMERIC: //数字
Double doubleValue = cell.getNumericCellValue();
String str = doubleValue.toString();
if(str.contains(".0")){
str = str.replace(".0", "");
}
Integer intValue = Integer.parseInt(str);
returnValue = intValue.toString();
break;
case HSSFCell.CELL_TYPE_STRING: //字符串
returnValue = cell.getStringCellValue();
break;
case HSSFCell.CELL_TYPE_BOOLEAN: //布尔
Boolean booleanValue=cell.getBooleanCellValue();
returnValue = booleanValue.toString();
break;
case HSSFCell.CELL_TYPE_BLANK: // 空值
returnValue = "";
break;
case HSSFCell.CELL_TYPE_FORMULA: // 公式
returnValue = cell.getCellFormula();
break;
case HSSFCell.CELL_TYPE_ERROR: // 故障
returnValue = "";
break;
default:
System.out.println("未知类型");
break;
}
}
return returnValue;
}