SpringBoot导入Excel表格
1、引入依赖
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>RELEASE</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>RELEASE</version>
</dependency>
2、创建导入表格工具类ImportExcelUtil
3、工具类
public class ImportExcelUtil {
public Map importExcel(MultipartFile file){
Map map = new HashMap();
Object obj = null;
InputStream ip = null;
try {
ip = file.getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
Workbook wb = null;
try {
wb = new XSSFWorkbook(ip);
} catch (IOException e) {
e.printStackTrace();
}
Sheet sheet = wb.getSheetAt(0);
Integer lastrow = sheet.getLastRowNum();
for(int i =0; i<lastrow; i++){
Row row = sheet.getRow(i);
for(int j = 0 ;j<row.getLastCellNum();j++){
Cell cell = row.getCell(j);
if(cell != null){
obj = gainExcelValue(cell);
map.put(i+","+j,obj);
}
}
}
return map;
}
4、获取单元格的值
public Object gainExcelValue(Cell cell) {
Object obj = null;
switch(cell.getCellType()) {
case BOOLEAN:
obj = cell.getBooleanCellValue();
break;
case ERROR:
obj = cell.getErrorCellValue();
break;
case FORMULA:
try {
obj = String.valueOf(cell.getStringCellValue());
} catch (IllegalStateException e) {
String valueOf = String.valueOf(cell.getNumericCellValue());
BigDecimal bd = new BigDecimal(Double.valueOf(valueOf));
bd = bd.setScale(2, RoundingMode.HALF_UP);
obj = bd;
}
break;
case NUMERIC:
obj = cell.getNumericCellValue();
break;
case STRING:
String value = cell.getStringCellValue();
value = value.replace(" ","");
value = value.replace("\n", "");
value = value.replace("\r", "");
obj = value;
break;
default:
break;
}
return obj;
}
只能简单的获取单元格中的数值