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 au.com.bytecode.opencsv.CSVWriter;
import com.ariestania.mysample.model.Person;
import com.ariestania.mysample.service.personService;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
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
 */
@Controller
public class CSVGeneratorController{

    @Autowired
    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) {
                    //name|email
                    csvDatas.add(new String[]{
                        person.getName(), person.getEmail()
                    });
                }
            }
                        
            String attch = "attachment; filename=\"" + sdf.format(today) + "report.csv\"";
            response.setContentType("text/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);
               
                osWriter.flush();                
            }
            
        } 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:

WordPress.com Logo

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

Google photo

You are commenting using your Google 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