Spring Boot + Apache Commons Export Data to CSV Example

Hello everyone, today we will learn how to export and download the data as a CSV file in a 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 Apache Commons' 3rd-party library. 


Technologies used 

  • Spring Boot
  • Apache Commons
  • Spring Data JPA
  • H2DB
  • Maven

Project directory



Maven[pom.xml] 

A Project Object Model or POM is the fundamental unit of work in Maven. It is an XML file that contains information about the project and configuration details utilized by Maven to build the project.
<?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.1.1.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>springboot_export_csv_apache_commons</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springboot_export_csv_apache_commons</name>
<description>Demo project for Spring Boot</description>

<properties>
<java.version>1.8</java.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.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-csv</artifactId>
<version>1.8</version>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>

</project>


Create Employee Model

package com.example.demo.model;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "employee")
public class Employee {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private String name;
private String email;
private String country;
private int age;
private String role;

public Employee() {
super();
}

public Employee(String name, String email, String country,
int age, String role) {
super();

this.name = name;
this.email = email;
this.country = country;
this.age = age;
this.role = role;
}

public String getRole() {
return role;
}

public void setRole(String role) {
this.role = role;
}

public long getId() {
return id;
}

public void setId(long id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getEmail() {
return email;
}

public void setEmail(String email) {
this.email = email;
}

public String getCountry() {
return country;
}

public void setCountry(String country) {
this.country = country;
}

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}

}


Create EmployeeRepository

package com.example.demo.repository;

import org.springframework.data.repository.CrudRepository;
import com.example.demo.model.Employee;

public interface EmployeeRepository
extends CrudRepository<Employee, Long> {

}


Create Employee Service

package com.example.demo.service;

import java.io.ByteArrayInputStream;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.demo.helper.CSVHelper;
import com.example.demo.model.Employee;
import com.example.demo.repository.EmployeeRepository;

@Service
public class EmployeeService {
@Autowired
EmployeeRepository employeeRepository;

public List<Employee> fetchAll() {
return (List<Employee>) employeeRepository.findAll();

}

public ByteArrayInputStream load() {
List<Employee> tutorials = fetchAll();

ByteArrayInputStream in = CSVHelper.employeesToCSV(tutorials);
return in;
}
}


Create CSVHelper

package com.example.demo.helper;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.List;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;
import org.apache.tomcat.util.http.fileupload.ByteArrayOutputStream;
import com.example.demo.model.Employee;

public class CSVHelper {

public static ByteArrayInputStream
employeesToCSV(List<Employee> employees)
{
final CSVFormat format = CSVFormat.DEFAULT.withHeader
("ID", "Name", "Email", "Age", "Country", "Role");

try (

ByteArrayOutputStream out =
new ByteArrayOutputStream();
CSVPrinter csvPrinter =
new CSVPrinter(new PrintWriter(out),
format);) {
for (Employee emp : employees) {
List<String> data = Arrays.asList(String
.valueOf(emp.getId()),
emp.getName(), emp.getEmail(),
String.valueOf(emp.getAge()),
emp.getCountry(),
emp.getRole());

csvPrinter.printRecord(data);
}

csvPrinter.flush();
return new ByteArrayInputStream(out.toByteArray());

} catch (IOException e) {
throw new RuntimeException
("fail to import data to CSV file: "
+ e.getMessage());
}
}
}


Create EmployeeController

package com.example.demo.controller;

import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import com.example.demo.service.EmployeeService;

@Controller
public class EmployeeController {

@Autowired
EmployeeService employeeService;

@GetMapping("/export-employees")
public ResponseEntity<InputStreamResource>
exportCSV(HttpServletResponse response)
throws Exception {

String filename = "employees.csv";
InputStreamResource file = new InputStreamResource
(employeeService.load());

return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION,
"attachment; filename=" + filename)
.contentType(MediaType
.parseMediaType("application/csv")).
body(file);

}
}


Spring Boot Main Driver

package com.example.demo;

import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import com.example.demo.model.Employee;
import com.example.demo.repository.EmployeeRepository;

@SpringBootApplication
public class SpringbootExportCsvDemoApplication
implements CommandLineRunner {

@Autowired
EmployeeRepository employeeRepository;

public static void main(String[] args) {
SpringApplication
.run(SpringbootExportCsvDemoApplication.class, args);
}

@Override
public void run(String... args) throws Exception {
List<Employee> employees = new ArrayList<>();

// create dummy employees
employees.add(new Employee("Dummy-1", "dummy1@example.com",
"India", 35, "Lead Tester"));
employees.add(new Employee("Dummy-2", "dummy2@srovoki.me",
"USA", 25, "Tester"));
employees.add(new Employee("Dummy-3", "dummy3@gmail.com",
"Japan", 29, "Sr.Tester"));
employees.add(new Employee("Dummy-1", "dummy1@example.com",
"India", 35, "Lead Tester"));
employees.add(new Employee("Dummy-2", "dummy2@srovoki.me",
"USA", 25, "Tester"));
employees.add(new Employee("Dummy-3", "dummy3@gmail.com",
"Japan", 29, "Sr.Tester"));
employees.add(new Employee("Dummy-1", "dummy1@example.com",
"India", 35, "Lead Tester"));
employees.add(new Employee("Dummy-2", "dummy2@srovoki.me",
"USA", 25, "Tester"));
employees.add(new Employee("Dummy-3", "dummy3@gmail.com",
"Japan", 29, "Sr.Tester"));
employees.add(new Employee("Dummy-1", "dummy1@example.com",
"India", 35, "Lead Tester"));
employees.add(new Employee("Dummy-2", "dummy2@srovoki.me",
"USA", 25, "Tester"));
employees.add(new Employee("Dummy-3", "dummy3@gmail.com",
"Japan", 29, "Sr.Tester"));
employees.add(new Employee("Dummy-1", "dummy1@example.com",
"India", 35, "Lead Tester"));
employees.add(new Employee("Dummy-2", "dummy2@srovoki.me",
"USA", 25, "Tester"));
employees.add(new Employee("Dummy-3", "dummy3@gmail.com",
"Japan", 29, "Sr.Tester"));
employeeRepository.saveAll(employees);
}
}

Download the complete source code - click here                                        

Local Setup and Run the application

Step1: Download or clone the source code from GitHub to a local machine - Click here


Step 2: mvn clean install


Step 3: Run the Spring Boot application - mvn spring-boot:run

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

Popular posts from this blog

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

Java Stream API - How to convert List of objects to another List of objects using Java streams?

Registration and Login with Spring Boot + Spring Security + Thymeleaf

Java, Spring Boot Mini Project - Library Management System - Download

ReactJS, Spring Boot JWT Authentication Example

Top 5 Java ORM tools - 2024

Java - Blowfish Encryption and decryption Example

Spring boot video streaming example-HTML5

Google Cloud Storage + Spring Boot - File Upload, Download, and Delete