<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.8</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.8</version>
</dependency
上面是需要引用的jar包,版本我选了一个比较稳定的,大家可根据自己的情况,自行选择。
废话就不多说了,我直接贴最有效的代码!
@PostMapping("/importExcel")
public void importExcel(MultipartFile file) {
//创建处理EXCEL的类
String fileName = file.getOriginalFilename(); //获取文件名,用于校验是不是exce
InputStream inputStream = null;
try{
inputStream = file.getInputStream();
Workbook wb = WorkbookFactory.create(inputStream);
// 得到第一个shell, excel 有很多工作表。
Sheet sheet = wb.getSheetAt(0);
// 得到Excel的行数
int totalRows = sheet.getPhysicalNumberOfRows();
// 得到Excel的列数(前提是有行数,有多少个字段。)
int totalCells = 0;
if (totalRows > 1 && sheet.getRow(0) != null) {
totalCells = sheet.getRow(0).getPhysicalNumberOfCells();
}
for (int i = 1; i < totalRows; i++) {
Row row = sheet.getRow(i);
if (row == null) {
continue;
}
Map<String, String> objectMap = new HashMap<>();
for (int j = 0; j < totalCells; j++) {
Cell cell = row.getCell(j);
DataFormatter dataFormatter = new DataFormatter();
String str = dataFormatter.formatCellValue(cell);//可以去掉位数后面的小数点。
JSONObject relationJson = relationMap.get(j);
objectMap.put(relationJson.getString("columnName"), str);
}
valueMap.put("form", objectMap);
}
}catch (Exception e){
}finally {
try{
if(inputStream!=null)inputStream.close();
}catch (Exception e){
e.printStackTrace();
}
}
}