Master CSV Processing in Spring Boot 3 with Super CSV – Full Code Guide

This article provides a comprehensive tutorial on using the Super CSV library in Spring Boot 3, covering Maven dependencies, core APIs for reading and writing CSV files, cell processors, handling irregular data, and a complete Spring MVC controller example for CSV download, all illustrated with code snippets and screenshots.

Spring Full-Stack Practical Cases
Spring Full-Stack Practical Cases
Spring Full-Stack Practical Cases
Master CSV Processing in Spring Boot 3 with Super CSV – Full Code Guide

Super CSV is a fast, programmer‑friendly open‑source Java library for reading and writing CSV files. It offers high configurability, supports POJOs, Maps, and Lists, and provides powerful cell processors for type conversion and validation, with optional Dozer and Joda‑Time extensions.

Dependency Management

<dependency>
  <groupId>net.sf.supercsv</groupId>
  <artifactId>super-csv</artifactId>
  <version>2.4.0</version>
</dependency>

If Dozer mapping is needed, add:

<dependency>
  <groupId>net.sf.supercsv</groupId>
  <artifactId>super-csv-dozer</artifactId>
  <version>2.4.0</version>
</dependency>

If Joda‑Time support is required, add:

<dependency>
  <groupId>net.sf.supercsv</groupId>
  <artifactId>super-csv-joda</artifactId>
  <version>2.4.0</version>
</dependency>

Core Classes

ICsvBeanReader and CsvBeanReader read CSV rows into Java beans; ICsvBeanWriter and CsvBeanWriter write beans to CSV. CellProcessor handles conversion and validation (e.g., NotNull(new ParseLong()), StrRegEx(emailRegex)). CsvPreference defines CSV format such as delimiter, quote character and line ending.

Reading CSV Files

Example using CsvBeanReader:

public static void main(String[] args) throws IOException {
  ClassPathResource resource = new ClassPathResource("csv/data.csv");
  Reader reader = new InputStreamReader(resource.getInputStream(), StandardCharsets.UTF_8);
  try (ICsvBeanReader beanReader = new CsvBeanReader(reader, CsvPreference.STANDARD_PREFERENCE)) {
    final String[] headers = beanReader.getHeader(true);
    final CellProcessor[] processors = getCellProcessors();
    User user;
    while ((user = beanReader.read(User.class, headers, processors)) != null) {
      System.err.println(user);
    }
  }
}

private static CellProcessor[] getCellProcessors() {
  final String emailRegex = "[a-z0-9\\._]+@[a-z0-9\\.]+";
  StrRegEx.registerMessage(emailRegex, "must be a valid email address");
  return new CellProcessor[] {
    new NotNull(new ParseLong()), // id
    new NotNull(),                // name
    new ParseInt(),               // age
    new Trim(),                   // address
    new StrRegEx(emailRegex)      // email
  };
}

Partial reading can ignore columns by setting the corresponding header to null. Key/value reading uses CsvMapReader, and irregular CSV files are handled with CsvListReader together with dynamic cell‑processor selection.

Writing CSV Files

Example using CsvBeanWriter:

public static void main(String[] args) {
  try (Writer writer = new FileWriter(new File("d:/user.csv"));
       ICsvBeanWriter beanWriter = new CsvBeanWriter(writer, CsvPreference.STANDARD_PREFERENCE)) {
    final String[] header = {"id", "name", "age", "address", "email"};
    final CellProcessor[] processors = getProcessors();
    beanWriter.writeHeader(header);
    List<User> list = List.of(
      new User(1L, "张三", 22, "四川", "[email protected]"),
      new User(2L, "李四", 25, "北京", "[email protected]"),
      new User(3L, "王五", 26, "新疆", "[email protected]"),
      new User(4L, "赵六", 23, "贵州", "[email protected]"),
      new User(5L, "田七", 28, "重庆", "[email protected]")
    );
    for (User user : list) {
      beanWriter.write(user, header, processors);
    }
  } catch (IOException e) {
    e.printStackTrace();
  }
}

Integration in Spring Boot

Service to fetch data:

@Service
public class UserService {
  private final UserRepository userRepository;
  public UserService(UserRepository userRepository) { this.userRepository = userRepository; }
  public List<User> queryUsers() { return userRepository.findAll(); }
}

Controller endpoint for CSV download:

@RestController
public class UserController {
  private final UserService userService;
  public UserController(UserService userService) { this.userService = userService; }

  @GetMapping("/download")
  public void download(HttpServletResponse response) throws IOException {
    List<User> list = userService.queryUsers();
    response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
    response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("用户列表.csv", "UTF-8"));
    try (Writer writer = new OutputStreamWriter(response.getOutputStream());
         ICsvBeanWriter beanWriter = new CsvBeanWriter(writer, CsvPreference.STANDARD_PREFERENCE)) {
      final String[] header = {"id", "name", "age", "address", "email"};
      final CellProcessor[] processors = getProcessors();
      beanWriter.writeHeader(header);
      for (User user : list) {
        beanWriter.write(user, header, processors);
      }
    }
  }
}

Illustrations

For projects that prefer an alternative, OpenCSV can be added with:

<dependency>
  <groupId>com.opencsv</groupId>
  <artifactId>opencsv</artifactId>
  <version>5.9</version>
</dependency>
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

data-processingSpring BootFile I/OCSVSpring MVCSuper CSV
Spring Full-Stack Practical Cases
Written by

Spring Full-Stack Practical Cases

Full-stack Java development with Vue 2/3 front-end suite; hands-on examples and source code analysis for Spring, Spring Boot 2/3, and Spring Cloud.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.