WIOijwww
WIOijwww

Reputation: 61

Exporting to CSV/Excel in Java

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) {
    }
}

Upvotes: 6

Views: 27490

Answers (4)

Guilherme
Guilherme

Reputation: 456

To do that, the CSV reader need to read the memory of your program. This is a little complex thing to do. So, save the file in a temp folder instead. There is no problem to do this sort of thing.

Upvotes: 0

dongpf
dongpf

Reputation: 1597

recommend HSSFWorkbook to easily read and write excel files. http://poi.apache.org/apidocs/org/apache/poi/hssf/usermodel/HSSFWorkbook.html

Upvotes: 0

Eric Hydrick
Eric Hydrick

Reputation: 3527

If you're not getting errors, check the directory where your code is. Without a specific path, your file is being saved there.

EDIT: Since the file is being saved and you want it to open automatically, use

Runtime.getRuntime().exec("results.csv"); 

(For Windows - opens the csv file in the default application for csv files)

Runtime.getRuntime().exec("open results.csv"); 

(For Mac - opens the csv file in the default application for csv files)

Upvotes: 1

Kai
Kai

Reputation: 39641

I would recommend using a framework like opencsv for that. It also does escaping and quoting for you.

Upvotes: 8

Related Questions