<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>5.2.3</version> <!-- 使用你需要的版本 -->
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>5.2.3</version> <!-- 使用你需要的版本 -->
</dependency>
public Boolean economicDataExcel(MultipartFile file) {
log.info("===============经济数据导入开始=============");
try (InputStream inputStream = file.getInputStream()) {
Workbook workbook = WorkbookFactory.create(inputStream);
Sheet sheet = workbook.getSheetAt(0); // 获取第一个sheet
List<AddGovEconomicDataDTO> list = new ArrayList<>();
// 从第六行开始读取(索引从0开始)
for (int rowNum = 5; rowNum <= sheet.getLastRowNum(); rowNum++) {
Row row = sheet.getRow(rowNum);
if (row == null || isRowEmpty(row)) {
// 如果行是空的,则结束读取
break;
}
AddGovEconomicDataDTO vo = new AddGovEconomicDataDTO();
// 名字 (第一列)
vo.setEnterpriseName(getValue(row.getCell(1)));
// 平台采购金额 (第二列)
vo.setPlatformProcurementAmount(new BigDecimal(StringUtils.isBlank(getValue(row.getCell(2))) ? "0"
: getValue(row.getCell(2))));
// 项目名称 (第三列)
vo.setEntryName(getValue(row.getCell(3)));
// 以此类推....
list.add(vo);
}
if (!CollectionUtils.isEmpty(list)){
// 保存数据save
}
log.info("===============经济数据导入结束=============");
return true;
} catch (Exception e) {
log.error("===============经济数据导入异常============= " + e.getMessage());
return false;
}
}
// 检查行是否为空
private boolean isRowEmpty(Row row) {
for (Cell cell : row) {
if (cell != null && cell.getCellType() != CellType.BLANK) {
return false; // 行中有非空单元格,因此行不为空
}
}
return true; // 行中所有单元格都是空的或不存在
}
// 返回列数据
public String getValue(Cell cell) {
switch (cell.getCellType()) {
case STRING:
return cell.getStringCellValue();
case NUMERIC:
if (DateUtil.isCellDateFormatted(cell)) {
return cell.getDateCellValue() + "";
} else {
return cell.getNumericCellValue() + "";
}
case BOOLEAN:
return cell.getBooleanCellValue() + "";
case FORMULA:
return cell.getCellFormula() + "'";
default:
return "";
}
}