Kotlin + Spring Boot + OpenCSV Export Data to CSV Example

Hello everyone, today we will learn how to export and download the data as a CSV file in a Kotlin + Spring Boot project. CSV stands for Comma-Separated-Values and it's a common format for doing a bulk data transfer between systems. For creating and parsing CSV files, we will use OpenCSV 3rd-party library.



Project Directory


Technologies used:

  • Kotlin
  • Spring Boot
  • OpenCSV
  • Spring Data JPA
  • H2DB
  • Maven

Maven[pom.xml]

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi=
                      "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
                       https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.7.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.knf.dev</groupId>
<artifactId>kotlin_springboot_export_csv_demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>kotlin_springboot_export_csv_demo</name>
<description>Demo project for Kotlin + Spring Boot</description>
<properties>
<java.version>1.8</java.version>
<kotlin.version>1.3.72</kotlin.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.module</groupId>
<artifactId>jackson-module-kotlin</artifactId>
</dependency>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-reflect</artifactId>
</dependency>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib-jdk8</artifactId>
</dependency>
<dependency>
<groupId>com.opencsv</groupId>
<artifactId>opencsv</artifactId>
<version>4.5</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<sourceDirectory>${project.basedir}/src/main/kotlin</sourceDirectory>
<testSourceDirectory>${project.basedir}/src/test/kotlin</testSourceDirectory>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-plugin</artifactId>
<configuration>
<args>
<arg>-Xjsr305=strict</arg>
</args>
<compilerPlugins>
<plugin>spring</plugin>
<plugin>jpa</plugin>
</compilerPlugins>
</configuration>
<dependencies>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-allopen</artifactId>
<version>${kotlin.version}</version>
</dependency>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-noarg</artifactId>
<version>${kotlin.version}</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
</project>

Creating the Document

package com.knf.dev.entity

import javax.persistence.*

@Entity
@Table(name = "employee")
class Employee {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
var id: Long = 0
var name: String? = null
var email: String? = null
var country: String? = null
var age = 0
var role: String? = null

constructor() : super() {}
constructor(
name: String?, email: String?, country: String?,
age: Int, role: String?
) : super() {
this.name = name
this.email = email
this.country = country
this.age = age
this.role = role
}
}

Creating the Repository

package com.knf.dev.repository

import com.knf.dev.entity.Employee
import org.springframework.data.jpa.repository.JpaRepository
import org.springframework.stereotype.Repository

@Repository
interface EmployeeRepository : JpaRepository<Employee, Long>

Creating the Controller

package com.knf.dev.controller

import com.knf.dev.repository.EmployeeRepository
import org.springframework.stereotype.Controller
import org.springframework.web.bind.annotation.*
import org.springframework.ui.Model
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PathVariable
import com.knf.dev.entity.Employee
import com.opencsv.CSVWriter
import com.opencsv.bean.StatefulBeanToCsv
import com.opencsv.bean.StatefulBeanToCsvBuilder
import org.springframework.http.HttpHeaders
import javax.servlet.http.HttpServletResponse

import java.util.ArrayList

@Controller
class EmployeeController(private val employeeRepository: EmployeeRepository) {
@GetMapping("/export-employees")
@Throws(Exception::class)
fun exportCSV(response: HttpServletResponse) {
//save Dummy Data
saveDummyEmployees()
// set file name and content type
val filename = "employees.csv"
response.contentType = "text/csv"
response.setHeader(
HttpHeaders.CONTENT_DISPOSITION,
"attachment; filename=\"$filename\""
)
// create a csv writer
val writer: StatefulBeanToCsv<Employee> = 
                           StatefulBeanToCsvBuilder<Employee>(response.writer)
.withQuotechar(CSVWriter.NO_QUOTE_CHARACTER).
                  withSeparator(CSVWriter.DEFAULT_SEPARATOR)
.withOrderedResults(false).build()
// write all employees to csv file
writer.write(employeeRepository.findAll())
}

//save Dummy Data
fun saveDummyEmployees() {
val employees: MutableList<Employee> = ArrayList()
// create dummy employees
employees.add(
Employee(
"Dummy-1", "dummy1@example.com",
"India", 35, "Lead Tester"
)
)
employees.add(
Employee(
"Dummy-2", "dummy2@srovoki.me",
"USA", 25, "Tester"
)
)
employees.add(
Employee(
"Dummy-3", "dummy3@gmail.com",
"Japan", 29, "Sr.Tester"
)
)
employees.add(
Employee(
"Dummy-1", "dummy1@example.com",
"India", 35, "Lead Tester"
)
)
employees.add(
Employee(
"Dummy-2", "dummy2@srovoki.me",
"USA", 25, "Tester"
)
)
employees.add(
Employee(
"Dummy-3", "dummy3@gmail.com",
"Japan", 29, "Sr.Tester"
)
)
employees.add(
Employee(
"Dummy-1", "dummy1@example.com",
"India", 35, "Lead Tester"
)
)
employees.add(
Employee(
"Dummy-2", "dummy2@srovoki.me",
"USA", 25, "Tester"
)
)
employees.add(
Employee(
"Dummy-3", "dummy3@gmail.com",
"Japan", 29, "Sr.Tester"
)
)
employees.add(
Employee(
"Dummy-1", "dummy1@example.com",
"India", 35, "Lead Tester"
)
)
employees.add(
Employee(
"Dummy-2", "dummy2@srovoki.me",
"USA", 25, "Tester"
)
)
employees.add(
Employee(
"Dummy-3", "dummy3@gmail.com",
"Japan", 29, "Sr.Tester"
)
)
employees.add(
Employee(
"Dummy-1", "dummy1@example.com",
"India", 35, "Lead Tester"
)
)
employees.add(
Employee(
"Dummy-2", "dummy2@srovoki.me",
"USA", 25, "Tester"
)
)
employees.add(
Employee(
"Dummy-3", "dummy3@gmail.com",
"Japan", 29, "Sr.Tester"
)
)
employeeRepository.saveAll(employees)
}
}

Driver

package com.knf.dev

import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication

@SpringBootApplication
class KotlinSpringbH2DBThymeleafApplication

fun main(args: Array<String>) {
runApplication<KotlinSpringbH2DBThymeleafApplication>(*args)
}

Run 

$ mvn spring-boot:run

Hit this URL in your local system, http://localhost:8080/export-employees

Open the downloaded CSV file


 Download source code



More Kotlin practice:

Popular posts from this blog

Spring boot video streaming example-HTML5

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Spring Boot + Mockito simple application with 100% code coverage

Spring Boot + OpenCSV Export Data to CSV Example

Custom Exception Handling in Quarkus REST API

DataTable-Pagination example with Spring boot, jQuery and ajax

Registration and Login with Spring Boot + Spring Security + Thymeleaf

Node JS mini projects with source code - free download

Spring boot web project free download:User Registration System

Java - Blowfish Encryption and decryption Example