Files
yjearth/src/main/java/com/yj/earth/business/controller/CsvController.java
ZZX9599 663235eb7e 推送
2025-10-22 11:44:18 +08:00

56 lines
2.1 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package com.yj.earth.business.controller;
import com.yj.earth.common.util.ApiResponse;
import com.yj.earth.vo.CsvField;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Tag(name = "CSV文件解析")
@RestController
@RequestMapping("/csv")
public class CsvController {
@GetMapping("/parseCsv")
@Operation(summary = "解析CSV文件")
public ApiResponse parseCsv(@Parameter(description = "文件路径") @RequestParam String filePath) {
Map<String, Object> response = new HashMap<>();
List<CsvField> fieldList = new ArrayList<>();
try {
File file = new File(filePath);
try (InputStreamReader reader = new InputStreamReader(new FileInputStream(file), "GBK");
CSVParser parser = new CSVParser(reader, CSVFormat.DEFAULT)) {
// 遍历所有行CSVRecord即一行数据
for (CSVRecord record : parser) {
// 确保每行至少有3列A、B、C列
if (record.size() >= 3) {
String label = record.get(1).trim();
String key = record.get(2).trim();
fieldList.add(new CsvField(key, label));
}
}
}
return ApiResponse.success(fieldList);
} catch (Exception e) {
return ApiResponse.failure(e.getMessage());
}
}
}