Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exporting SQL query result to csv or Excel

Tags:

java

sql

csv

excel

I want to write the result of a SQL query to a csv or Excel file and save it in a particular folder. I have following requests:

  1. I would like to know, if this can be achieved using a Java program which can be reused for any SQL query result.
  2. I would also like to know, if this can be used for different databases (Oracle, MySQL, SQL Server, etc.).
  3. I plan to attach the saved file to an email. Is it possible to export SQL query results to an email directly?.
like image 537
sathish kumar Avatar asked Dec 19 '11 15:12

sathish kumar


People also ask

Can we export SQL query results to Excel?

Method Number 1 – Copy Grid results and paste into Excel After ensuring results to grid turned on, Execute your query, right-click the top left-hand corner of the results grid. Right-click on the database you want to export from. Then Select tasks and “Export Data”. The SQL Server Wizard will startup.

How do I export SQL query results to Excel automatically?

Go to "Object Explorer", find the server database you want to export to Excel. Right-click on it and choose "Tasks" > "Export Data" to export table data in SQL. Then, the SQL Server Import and Export Wizard welcome window pop up.


1 Answers

With use of openCSV API, you can export your data in csv file.

CSVWriter writer = new CSVWriter(new FileWriter("yourfile.csv"), '\t');
Boolean includeHeaders = true;

java.sql.ResultSet myResultSet = .... //your resultset logic here

writer.writeAll(myResultSet, includeHeaders);

writer.close();
like image 118
Piyush Ghediya Avatar answered Sep 24 '22 08:09

Piyush Ghediya