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;

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s