前几天实习过程中,遇到了一个需求,导入excel表单,对数据进行分析。上网也搜集到了利用Apache的POI可以对excel表单进行操作。接下来就是具体的实战例子:
前置条件:搭建一个Springboot项目,前后台都基本写好。
具体的POI API文档链接:http://poi.apache.org/apidocs/3.17/
1、添加依赖
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
2、编写接口
@RestController
@Slf4j
public class UploadController {
@RequestMapping("/uploadExcel")
public String uploadExcel(@RequestParam(required = true,value = "excelFile") MultipartFile excelFile) {
Workbook wb = null;
try{
String fileName = excelFile.getOriginalFilename();
if (fileName.endsWith("xls")) {
//Excel 2003
wb = new HSSFWorkbook(excelFile.getInputStream());
} else if (fileName.endsWith("xlsx")) {
// Excel 2007/2010
wb = new XSSFWorkbook(excelFile.getInputStream());
}
} catch (Exception e) {
log.error(e.getMessage());
}
//获取第几个excel表格,下标从0开始
Sheet sheet = wb.getSheetAt(0);
//获取表格最后一行的行号,下标从0开始
int lastRowNum = sheet.getLastRowNum();
List<Map<Integer,String>> list = new ArrayList<>(lastRowNum);
Map<Integer,String> map;
for (int i = 0; i < lastRowNum; i++) {
Row row = sheet.getRow(i);
//获取该行第几个单元格,下标从0开始
//先将单元格转换成String类型的
row.getCell(0).setCellType(CellType.STRING);
row.getCell(1).setCellType(CellType.STRING);
String firstValue = row.getCell(0).getStringCellValue();
String secondValue = row.getCell(1).getStringCellValue();
map = new TreeMap<>();
map.put(1,firstValue);
map.put(2,secondValue);
list.add(map);
}
String jsonString = JSON.toJSONString(list);
return jsonString;
}
}
3、测试结果
将excel表格创建好,接着用postman进行测试。
测试成功!