添加依赖
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.9</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.9</version>
</dependency>
检查文件类型
public static void checkFile(MultipartFile file) throws IOException{
if(null == file){
throw new FileNotFoundException("文件不存在!");
}
String fileName = file.getOriginalFilename();
if(!fileName.endsWith("xls") && !fileName.endsWith("xlsx")){
throw new IOException(fileName + "不是excel文件");
}
}
获得工作簿(Workbook)
public static Workbook getWorkBook(MultipartFile file) {
String fileName = file.getOriginalFilename();
Workbook workbook = null;//创建Workbook工作薄对象,表示整个excel
try {
InputStream is = file.getInputStream();
//根据文件后缀名不同(xls和xlsx)获得不同的Workbook实现类对象
if(fileName.endsWith("xls")){
workbook = new HSSFWorkbook(is);//2003
}else if(fileName.endsWith("xlsx")){
workbook = new XSSFWorkbook(is);//2007
}
} catch (IOException e) {
System.out.println(e.getMessage());
}
return workbook;
}
获得单元格的字符串值
public static String getCellValue(Cell cell){
String cellValue = "";
if(cell == null){
return cellValue;
}
if(cell.getCellType() == Cell.CELL_TYPE_NUMERIC){//把数字当成String来读,避免出现1读成1.0的情况
cell.setCellType(Cell.CELL_TYPE_STRING);
}
//判断数据的类型
switch (cell.getCellType()){
case Cell.CELL_TYPE_NUMERIC: //数字
cellValue = String.valueOf(cell.getNumericCellValue());
break;
case Cell.CELL_TYPE_STRING: //字符串
cellValue = String.valueOf(cell.getStringCellValue());
break;
case Cell.CELL_TYPE_BOOLEAN