要在 Java 后端中获取 Excel 中的值,并去除重复数据,可以使用 Apache POI 库来操作 Excel 文件。

首先,您需要在 pom.xml 文件中添加 Apache POI 的依赖:

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>4.1.2</version>
</dependency>

接下来,您可以编写一个 Spring Boot 的 Controller 来处理 Excel 文件的读取和去重操作。以下是一个示例代码:

import org.apache.poi.ss.usermodel.*;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

@RestController
@RequestMapping("/excel")
public class ExcelController {

    private static final String FILE_PATH = "path_to_your_excel_file.xlsx";

    @GetMapping("/distinct-values")
    public ResponseEntity<Set<String>> getDistinctValues() {
        Set<String> distinctValues = new HashSet<>();

        try (Workbook workbook = WorkbookFactory.create(new FileInputStream(FILE_PATH))) {
            Sheet sheet = workbook.getSheetAt(0);

            // Iterate through each row in the sheet
            for (Row row : sheet) {
                Cell cell = row.getCell(0); // Assuming the value is in the first column

                if (cell != null && cell.getCellType() == CellType.STRING) {
                    distinctValues.add(cell.getStringCellValue());
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            // Handle exception
        }

        return ResponseEntity.ok(distinctValues);
    }
}

在上述代码中,您需要将 FILE_PATH 变量替换为实际的 Excel 文件路径。getDistinctValues() 方法将返回一个包含去重后的值的 Set 对象。

最后,您可以通过访问 /excel/distinct-values 端点来获取去重后的 Excel 值。

请注意,此示例假设 Excel 文件的第一列包含要获取的值。如果您的 Excel 文件结构不同,您需要相应地修改代码来读取正确的单元格。

SpringBoot 使用 Apache POI 从 Excel 文件中获取去重后的值

原文地址: https://www.cveoy.top/t/topic/qqKb 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录