pom.xml导入依赖
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.11</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.11</version>
</dependency>
导入xlsx结尾的Excel示例代码
@PostMapping("importExcel")
public void importExcel(@RequestParam("file") MultipartFile file) throws IOException {
List<EhrZoningCode> ehrZoningCodes = new ArrayList<>();
XSSFWorkbook wb = new XSSFWorkbook(file.getInputStream());//获取上传的文件流
XSSFSheet sheet = wb.getSheetAt(0);//根据页面index 获取sheet页
int lastRowNum = sheet.getLastRowNum();
for (int i = 1; i <= lastRowNum; i++) {
XSSFRow row = sheet.getRow(i);
if (row != null) {
List<String> list = new ArrayList<>();
for (Cell cell : row) {
if (cell != null) {
cell.setCellType(Cell.CELL_TYPE_STRING);
String value = cell.getStringCellValue();
if (value != null && !"".equals(value.trim()))
list.add(value);
}
}
if (!list.isEmpty()) {
EhrZoningCode ehrZoningCode = new EhrZoningCode();
ehrZoningCode.setZoningCode(row.getCell(0).getStringCellValue());
ehrZoningCode.setZoningName(row.getCell(1).getStringCellValue());
ehrZoningCode.setZoningLevel(row.getCell(2).getStringCellValue());
ehrZoningCode.setZoningStatus("1");
ehrZoningCodes.add(ehrZoningCode);
log.info("list:{}", ehrZoningCodes);
}
}
}
if (!ehrZoningCodes.isEmpty()) {
//入库
}
}
实体类
@Data
public class EhrZoningCode {
private Long zoningId; //id
private String zoningCode; //区域码
private String zoningName; //区域名称
private String zoningLevel; //区域层级
private String zoningType; //区域类型
private String zoningStatus; //区域状态
private String pyCode; //区域拼音
}
文章展示了如何在Java中通过ApachePOI库读取xlsx格式的Excel文件,从上传的MultipartFile对象中获取文件流,遍历工作表中的行和单元格,提取数据并存储到EhrZoningCode实体类中,准备进行数据库入库操作。
429

被折叠的 条评论
为什么被折叠?



