[Spring Boot] Upload and Parse a CSV File



How to Upload and Parse a CSV File using Spring Boot with OpenCSV

Uploading and parsing CSV files is a common task in many applications, especially when dealing with data import/export functionalities. Spring Boot, a popular Java framework, provides a convenient way to handle file uploads and parsing. In this tutorial, we'll explore how to upload and parse a CSV file using Spring Boot and the OpenCSV library. OpenCSV is a third-party library that simplifies the CSV parsing process in Java applications.

Prerequisites

Before we get started, make sure you have the following prerequisites in place:

1. Java Development Kit (JDK): Install JDK 8 or later on your machine.
2. Spring Boot: Set up a Spring Boot project. You can use Spring Initializr (https://start.spring.io/) or your preferred method.
3. OpenCSV Library: Add the OpenCSV dependency to your project. You can do this by including the following dependency in your `pom.xml` if you're using Maven:

<dependency>
    <groupId>com.opencsv</groupId>
    <artifactId>opencsv</artifactId>
    <version>5.5.2</version>
</dependency>

Step 1: Create the File Upload Form

First, let's create a simple HTML form that allows users to upload a CSV file. Create an HTML file named `upload.html` in the `src/main/resources/templates` directory of your Spring Boot project:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>CSV File Upload</title>
</head>
<body>
    <h2>Upload a CSV File</h2>
    <form th:action="@{/upload}" th:method="post" enctype="multipart/form-data">
        <input type="file" name="file" accept=".csv">
        <button type="submit">Upload</button>
    </form>
</body>
</html>




Step 2: Create the Controller

Now, let's create a controller that handles the file upload and parsing. Create a Java class named `CsvController`:

import com.opencsv.CSVReader;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStreamReader;

@Controller
public class CsvController {

    @RequestMapping("/")
    public String uploadForm() {
        return "upload";
    }

    @PostMapping("/upload")
    public String uploadFile(@RequestParam("file") MultipartFile file, Model model) {
        if (file.isEmpty()) {
            model.addAttribute("message", "Please select a CSV file to upload.");
            return "upload";
        }

        try (CSVReader reader = new CSVReader(new InputStreamReader(file.getInputStream()))) {
            String[] nextLine;
            while ((nextLine = reader.readNext()) != null) {
                // Process each row of the CSV file
                // You can access each cell using nextLine[index]
            }
        } catch (IOException e) {
            model.addAttribute("message", "Error occurred while parsing the CSV file.");
            return "upload";
        }

        model.addAttribute("message", "CSV file uploaded and parsed successfully.");
        return "upload";
    }
}

Step 3: Run the Application

Now that you have the HTML form and the controller in place, you can run your Spring Boot application. Access the form by navigating to `http://localhost:8080/` in your web browser. You'll be able to upload a CSV file using the form, and upon submission, the controller will parse the uploaded file using OpenCSV.

Remember that this example provides a basic foundation for handling CSV uploads and parsing. You can extend it to include more advanced features such as error handling, data validation, and database integration based on your application's requirements.

That's it! You've successfully learned how to upload and parse a CSV file using Spring Boot and the OpenCSV library. Happy coding!


Post a Comment

Previous Post Next Post