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();
}
}