Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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) {
    }
}
like image 823
WIOijwww Avatar asked Aug 24 '11 15:08

WIOijwww


People also ask

Can we create CSV file using Java?

Writing a CSV file is as simple as reading. Create an instance of CSVWriter by passing FileWriter object as parameter and start writing data to CSV file using methods of CSVWriter Class. After writing data we need to close CSVWriter connection by calling close() method of CSVWriter class.


2 Answers

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

like image 165
Kai Avatar answered Sep 17 '22 23:09

Kai


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)

like image 21
Eric Hydrick Avatar answered Sep 20 '22 23:09

Eric Hydrick