Exporting to CSV/Excel in Java

Posted by WIOijwww on Stack Overflow See other posts from Stack Overflow or by WIOijwww
Published on 2011-08-24T15:31:05Z Indexed on 2014/06/11 3:25 UTC
Read the original article Hit count: 121

Filed under:
|
|
|

I'm trying to export data into a CSV file through Java and I've got some code to do it but it doesn't seem to be outputting the CSV file. Could someone tell me what's wrong? What I would like to do is rather than saving the file somewhere, I would like it to be directly exported to the user.

EDIT: Just in case it's not clear, I don't want the file to be saved anywhere but would like it to be outputted automatically to the user i.e. they click export and get the "Run/Save results.csv" window and they open the file. Currently the file is getting saved so I know that the method seems to work, just in the opposite way that I want it to.

public static void writeToCSV(List<Map> objectList) {
    String CSV_SEPARATOR = ",";
    try {
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(
                new FileOutputStream("results.csv"), "UTF-8"));
        for (Map objectDetails : objectList) {
            StringBuffer oneLine = new StringBuffer();
            Iterator it = objectDetails.values().iterator();

            while (it.hasNext()) {
                Object value = it.next();

                if(value !=null){
                    oneLine.append(value.toString());
                    }

                if (it.hasNext()) {
                    oneLine.append(CSV_SEPARATOR);
                }
            }
            bw.write(oneLine.toString());
            bw.newLine();
        }
        bw.flush();
        bw.close();
    } catch (UnsupportedEncodingException e) {
    } catch (FileNotFoundException e) {
    } catch (IOException e) {
    }
}

© Stack Overflow or respective owner

Related posts about java

Related posts about excel