Nancy
Nancy

Reputation: 51

How to download data as csv from database using java?

I need to download the csv file from database using database.

I have jdbc connection and execute the query , get the data from database.Those values are download as csv format using java class.

Java class:
String filename="Cases.csv";
//here database connection.


ResultSet rst= stmt.executeQuery(qry);
    System.out.println("1"+rst);
    if(rst.next())
    {

    Content=rst.getString("USER_details");

    }
    //ServletOutputStream out = null;
    //out.println(Content);
    System.out.println("1"+Content);
    byte requestBytes[] = Content.getBytes();
    ByteArrayInputStream bis = new ByteArrayInputStream(requestBytes);
    response.reset();
    response.setContentType("application/text");
    response.setHeader("Content-disposition","attachment; filename=" +filename);
    byte[] buf = new byte[1024];
    int len;
    while ((len = bis.read(buf)) > 0){
    response.getOutputStream().write(buf, 0, len);
    }
    bis.close();
    response.getOutputStream().flush(); 
    }
    catch(Exception e){
    e.printStackTrace();
    }

How to get all values from database to csv format ?

Upvotes: 1

Views: 2870

Answers (1)

gustafc
gustafc

Reputation: 28865

OpenCSV supports exporting a ResultSet to CSV:

CSVWriter writer = ...;
ResultSet rs = ...;
writer.writeAll(rs, true);

Upvotes: 3

Related Questions