How To Write CSV File Using OpenCSV

In this sample, I made CSV File as response to client.
CSVWriter csvWriter = new CSVWriter(osWriter,’|’); means I use “I” as the separator.
csvWriter.writeAll(csvDatas, false); means do not use quote mark (“) when the data is String.

import com.ariestania.mysample.model.Person;
import com.ariestania.mysample.service.personService;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

 * @author ariestania.winda
public class CSVGeneratorController{

    private PersonService personService;

    @RequestMapping(value = "/generatecsv", method = RequestMethod.GET)
    public String generateCSV(HttpServletRequest request, HttpServletResponse response) {
        Date today = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        SimpleDateFormat csvDateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
        try {
            List<Person> persons = personService.getAllVerified();
            List<String[]> csvDatas = new ArrayList<>();
            if (!persons.isEmpty()) {
                for (Person person : persons) {
                    csvDatas.add(new String[]{
                        person.getName(), person.getEmail()
            String attch = "attachment; filename=\"" + sdf.format(today) + "report.csv\"";
            response.setHeader("Content-Disposition", attch);
	    //start to write CSV File as response
            try (ServletOutputStream os = response.getOutputStream();
				OutputStream buffOs = new BufferedOutputStream(os); 
				OutputStreamWriter osWriter = new OutputStreamWriter(buffOs)) {
                CSVWriter csvWriter = new CSVWriter(osWriter,'|');
                csvWriter.writeAll(csvDatas, false);
        } catch (IOException e) {
            System.out.println("failed to generate CSV file : " + e.getMessage());
        return null;

How To Upload and Read CSV File On SpringMVC Using OpenCSV

In this function, I use OpenCSV library to help me read csv file. You can read more about OpenCSV on their website.

The form on my jsp:

<form action="${baseURL}/uploadfile" method="POST" enctype="multipart/form-data" >
    <div class="form-group">
        <label>File input</label>
        <input type="file" name="file"/>
    <div class="form-group">
        <button type="submit" id="upload">Upload</button>

My controller: Continue reading “How To Upload and Read CSV File On SpringMVC Using OpenCSV”