一、需要导入的jar包
<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>
二、POIAPI连接
三、代码如下
/**
* 获取上传的excel 解析数据
*
* @param file
* 文件
* @param excelName
* 文件名
* @return
* @throws IOException
* @throws InvalidFormatException
*/
@PostMapping("/readexcel")
public List<WorkstationExcel> uploadExcel(@RequestParam MultipartFile file, @RequestParam String excelName) throws IOException, InvalidFormatException {
List<WorkstationExcel> dataList = null;
try (InputStream in = file.getInputStream()) {
Workbook wb = WorkbookFactory.create(in);
// 获取第一个sheet
Sheet sheet = wb.getSheetAt(0);
// 获取最大行数
int rownum = sheet.getPhysicalNumberOfRows();
// 获取第一行
Row row = sheet.getRow(0);
// 存放表中的数据
dataList = new ArrayList<WorkstationExcel>();
// 循环行
for (int i = 1; i < rownum; i++) {
WorkstationExcel we = new WorkstationExcel();
row = sheet.getRow(i);
if (row != null) {
we.name = getCellFormatValue(row.getCell(0));
we.ip = getCellFormatValue(row.getCell(1));
we.description = getCellFormatValue(row.getCell(2));
} else {
continue;
}
System.err.println("名称:" + we.name + "------" + "IP:" + we.ip + "------" + "描述:" + we.description);
dataList.add(we);
}
}
return dataList;
}
public String getCellFormatValue(Cell cell) {
String cellValue = "";
if (cell == null) {
return cellValue;
}
// 判断cell类型 getCellType()
switch (cell.getCellType()) {
case Cell.CELL_TYPE_NUMERIC: {
// 获取单元格的值作为数字 getNumericCellValue()
cellValue = String.valueOf((int)cell.getNumericCellValue());
break;
}
case Cell.CELL_TYPE_FORMULA: {
// 判断cell是否为日期格式
if (DateUtil.isCellDateFormatted(cell)) {
// 转换为日期格式YYYY-mm-dd
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date d = cell.getDateCellValue();
if (d != null) {
cellValue = sdf.format(d);
}
} else {
// 数字
cellValue = String.valueOf(cell.getNumericCellValue());
}
break;
}
case Cell.CELL_TYPE_STRING: {
cellValue = cell.getRichStringCellValue().getString();
break;
}
}
return cellValue;
}
@SuppressWarnings("unused")
private class WorkstationExcel {
/**
* 工作站名 如 001
*/
public String name;
/**
* 工作站ip
*/
public String ip;
/**
* 描述
*/
public String description;
}
四、Excel表如下
名称 | IP | 描述 |
GYG4 | 127.0.0.33 | sfs |
DFSA | 127.0.46.3 | fsd |
ADAS | 172.26.6.15 | dfd |
WSFS | 153.6.5.23 | dgs |
五、获取数据结果