Question

I would like to know how to export the contents of a table or the data from a query to an Excel file. Also wich is the file extension that is better to export to, xls or csv?

Thanks in advance.


Edit: What i want is the user to to be able to export the contents of a JTable -containing the results from a query- to an Excel compatible file, by pressing a button.

I don't know what is the best way to do it? I found various ways but i'm not sure which one to follow. Is it possible to generate a JasperReport then export tha same data to excel?


Edit2:Ok so i decided to export to .csv like most of you suggest. My last question is which one is better to use, opecsv or javacsv? Both seem really easy to use.

Thanks!

Was it helpful?

Solution

Exporting to csv is easier - and could be done manually in a pinch depending on the data (Each new row is a new line, and cell values are seperated by a comma) - There are open source libraries available for this (http://opencsv.sourceforge.net/), and the code for copying a resultset to your output should be trivial

OTHER TIPS

If you absolutely need Excel, use the Apache POI library.

You have to create text file (csv) and write the result of database.

PrintWriter out
   = new PrintWriter(new BufferedWriter(new FileWriter("foo.csv")));

while(rs.next())
{
  out.println(String.format("%s,%s,%s",rs.getString(1),rs.getString(2),rs.getString(3));
}

In addition to the answers already given, I would like to say that I would prefer CSV.

CSV is application-agnostic and you could manipulate the data later on with any other language/program (Python, R, Java, Excel, etc).

I had good success with jXLS: http://jxls.sourceforge.net/

this lets you use JSP-like tags in a native Excel template with all the formatting etc. You pass data to substitute into that Excel template from Java API calls, via a Map structure (analogous to request scope vars.)

This is a good lighter-weight alternative to JasperReports if you just want formatted Excel output.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top