fbpx

Spring Boot CSV export – OpenCSV

1. Introduction

Last week, we’ve learned how to upload CSV files in Spring Boot REST API. I’ve also mentioned, that conversion of CSV files is almost always an important part of any application.

In this guide, I will teach you how to implement Spring Boot CSV export functionality using OpenCSV library and Kotlin.

2. Imports

But before we will start coding, let’s add the necessary dependencies:

    implementation("com.opencsv:opencsv:5.2")
    implementation("org.springframework.boot:spring-boot-starter-web")

Technically, we do not need web dependency to work with the CSV export, but in this tutorial, I will show you also the two ways in which we can create REST endpoints.

3. Create a User Class

As the second step, let’s create a simple User class, which will be used later:

class User(
    val id: Long,
    val email: String,
    val name: String
)

4. Create a User Service

As the next step, let’s implement the UserService class:

@Service
class UserService {
    fun findAllUsers() =
        listOf(
            User(1, "piotr@codersee.com", "Piotr"),
            User(2, "adam@codersee.com", "Adam"),
            User(3, "john@codersee.com", "John"),
            User(4, "karim@codersee.com", "Karim")
        )
}

As you can see, this simple class contains one function, which returns the immutable list of users. This implementation might be a good entry point for connecting to some database, or any other data source later.

5. Create REST Controller

As the last step, before we will head to the CSV service, let’s implement the UserController class with two functions:

@RestController
class UserController(
    private val csvService: CsvService
) {
    @PostMapping("/api/user/csv")
    fun getAllUsersCsvExport(response: HttpServletResponse) {
        csvService.exportUserListToCsv(response.writer)
    }

    @PostMapping("/api/user/csv/string")
    fun getAllUsersCsvExportWihStringWriter(): ResponseEntity {
        val result = csvService.exportUserListToCsvWithStringWriter()

        return ResponseEntity.ok(result.toString())
    }
}

In the first scenario, we will use the HttpServletResponse object provided by the servlet container to write our response using its PrintWriter. In the second scenario, we will use our own StringWriter object to return the CSV as a String (this method might be easily converted to send the export CSV as a part of some custom response object).

6. Create CSV Service

After the above steps are done, we can start exploring the possibilities provided by the OpenCSV library. Let’s create the CsvService class and implement the prepareMappingStrategy:

@Service
class CsvService(
    private val userService: UserService
) {
    private fun prepareMappingStrategy(): ColumnPositionMappingStrategy {
        val columns = arrayOf("id", "email", "name")

        val strategy = ColumnPositionMappingStrategy()
        strategy.setColumnMapping(*columns)
        strategy.type = User::class.java

        return strategy
    }
}

The prepareMappingStrategy function returns the ColumnPositionMappingStrategy object, which we will use for write operations later. Please notice, that the values of the columns array need to match the fields of the User class.

6.1. Export Beans With Default Values

Let’s start simply by exporting the list of all users using default values:

fun exportUserListToCsv(writer: PrintWriter) {
    val users = userService.findAllUsers()

    val mappingStrategy = prepareMappingStrategy()
    val bean = StatefulBeanToCsvBuilder(writer)
        .withMappingStrategy(mappingStrategy)
        .build()

    bean.write(users)
}

As the result, we will get the list in the following format:

"1","piotr@codersee.com","Piotr"
"2","adam@codersee.com","Adam"
"3","john@codersee.com","John"
"4","karim@codersee.com","Karim"

6.2. Export Beans Without the Quote Chars

If for some reason, we would like to remove the quote character, we can use the withQuotechar function:

fun exportUserListToCsvWithoutQuoteChar(writer: PrintWriter) {
    val users = userService.findAllUsers()

    val mappingStrategy = prepareMappingStrategy()
    val bean = StatefulBeanToCsvBuilder(writer)
        .withMappingStrategy(mappingStrategy)
        .withQuotechar(CSVWriter.NO_QUOTE_CHARACTER)
        .build()

    bean.write(users)
}

This time, our CSV export will be looking like this:

1,piotr@codersee.com,Piotr
2,adam@codersee.com,Adam
3,john@codersee.com,John
4,karim@codersee.com,Karim

6.3. Export Beans With Custom Separator

Although the CSV acronym stands for the comma-separated-values, we can easily set our custom separator using the withSeparator function:

fun exportUserListToCsvCustomSeparator(writer: PrintWriter) {
    val users = userService.findAllUsers()

    val mappingStrategy = prepareMappingStrategy()
    val bean = StatefulBeanToCsvBuilder(writer)
        .withMappingStrategy(mappingStrategy)
        .withSeparator(';')
        .build()

    bean.write(users)
}

After this operation, our CSV export will have the following structure:

"1";"piotr@codersee.com";"Piotr"
"2";"adam@codersee.com";"Adam"
"3";"john@codersee.com";"John"
"4";"karim@codersee.com";"Karim"

6.4. Export Beans With Custom Line Ending

By default, the line feed is used as the line ending. To set our own one, we can use the withLineEnd function:

fun exportUserListToCsvCustomLineEnd(writer: PrintWriter) {
    val users = userService.findAllUsers()

    val mappingStrategy = prepareMappingStrategy()
    val bean = StatefulBeanToCsvBuilder(writer)
        .withMappingStrategy(mappingStrategy)
        .withLineEnd("||\n")
        .build()

    bean.write(users)
    writer.close()
}

As you might have guessed, each line of the exported file will be ended with two vertical bars:

"1","piotr@codersee.com","Piotr"||
"2","adam@codersee.com","Adam"||
"3","john@codersee.com","John"||
"4","karim@codersee.com","Karim"||

6.5. Export Beans With StringWriter

In all of the above examples, we’ve been using the PrintWriter object obtained from the HttpServletResponse. As the last example, I want to show you how to export the data using created StringWriter:

fun exportUserListToCsvWithStringWriter(): StringWriter {
    val users = userService.findAllUsers()

    val mappingStrategy = prepareMappingStrategy()
    val writer = StringWriter()
    val bean = StatefulBeanToCsvBuilder(writer)
        .withMappingStrategy(mappingStrategy)
        .build()
    bean.write(users)

    writer.close()
    return writer
}

To get the content of the CSV export, all we need to do is to invoke the toString method on the returned writer object (as we already did in our UserController).

7. Conclusion

And that would be all for this article. We’ve learned how easy it is to create a Spring Boot CSV export functionality using OpenCSV library and Kotlin.

I hope you really enjoyed this guide and that the Codersee really helps you to get a better understanding of programming. If you really think, that I am doing good work with my tutorials, would you be so kind and share our page with your friends? It’s the beginning of our journey and it is really hard to break through among many other pages offering programming tutorials. With your help, we would be able to build a really great community based on knowledge sharing and respect. Thank you in advance!

And of course, please find the source code in this GitHub repository.

Share on facebook
Share on twitter
Share on linkedin

Leave a Comment

Your email address will not be published. Required fields are marked *

Subscribe to our Newsletter

Join the community and get free eBooks.

Image shows the covers of free ebooks accessible for newsletter subscribers.

You may opt out any time. Terms of Use and Privacy Policy

Find us also on...

Join the FREE weekly newsletter and get two free eBooks as well:

Image shows the covers of free ebooks accessible for newsletter subscribers.

You may opt out any time. Terms of Use and Privacy Policy

To make Codersee work, we log user data. By using our site, you agree to our Privacy Policy and Terms of Use.