poi读取表单数据

J2EE 码拜 8年前 (2016-09-15) 1232次浏览
利用poi读取表单类型的数据,请各位高手给点思路poi读取表单数据
解决方案

100

首先获取文件类型
public final static String getFileType(File excelFile)
{
String filetype = null;
byte[] b = new byte[50];
try{
InputStream is = new FileInputStream(excelFile);
is.read(b);
filetype = getFileTypeByStream(b);
is.close();
}catch(FileNotFoundException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
return filetype;
}
再根据excel不同的类型,使用poi不同的方法(HSSFWorkbook 或 XSSFWorkbook )读取excel里的值,再对值组装
List<String> paramList = new ArrayList<String>();
Workbook hssfWorkbook = null;
String type = getFileType(file);
if(“xls”.equals(type)){
hssfWorkbook = new HSSFWorkbook(is);
}else if(“xlsx”.equals(type)){
hssfWorkbook = new XSSFWorkbook(file.getPath());
}
Sheet hssfSheet = hssfWorkbook.getSheetAt(numSheet);
Row firstRow = hssfSheet.getRow(rownum);
if(null != firstRow){
for(int firstRowCellNum = 0; firstRowCellNum < firstRow.getLastCellNum(); firstRowCellNum++){
Cell hssfCell = firstRow.getCell(firstRowCellNum);
if(hssfCell == null){
continue;
}else{
//获取单元格的值
if(null != getValue(hssfCell)){
String value =  getValue(hssfCell).toString();
paramList.add(value);

}

}
}else{
}

从paramlist 获取A1和B1的值,要本人手动组装

//获取单元格的值
private static Object getValue(Cell hssfCell){
if(hssfCell.getCellType() == HSSFCell.CELL_TYPE_BOOLEAN){
return hssfCell.getBooleanCellValue();
}
else if(hssfCell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC){
if(HSSFDateUtil.isCellDateFormatted(hssfCell)){
SimpleDateFormat sf = new SimpleDateFormat(“yyyy-MM-dd”);
return sf.format(hssfCell.getDateCellValue());
}else{
hssfCell.setCellType(HSSFCell.CELL_TYPE_STRING);
return hssfCell.getStringCellValue();
}
}else if(hssfCell.getCellType() == HSSFCell.CELL_TYPE_FORMULA){
return hssfCell.getNumericCellValue();
}
else if(hssfCell.getCellType() == HSSFCell.CELL_TYPE_STRING){
return hssfCell.getStringCellValue().trim();
}
else if(hssfCell.getCellType() == HSSFCell.CELL_TYPE_BLANK){
return null;
}
else{
return hssfCell.getErrorCellValue();
}
}


CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明poi读取表单数据
喜欢 (0)
[1034331897@qq.com]
分享 (0)