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;
    }
    
}

Advertisements

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>
    <br/><br/>
    <div class="form-group">
        <button type="submit" id="upload">Upload</button>
    </div>
</form>

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