1

The reason may be the the short of knowledge in java :( ,so I'm asking this question,

Here in this piece of code I'm getting dynamic value(from a jsp page) :

<form action="">
  <% 
    Class.forName("com.mysql.jdbc.Driver");
    Connection con = DriverManager.getConnection("jdbc:mysql://localhost/apps","root","root");
    Statement stmt = con.createStatement();
    String sql = "select * from info;";
    ResultSet rs = stmt.executeQuery(sql);
    System.out.println(sql);
    System.out.println("hi Tirtha");
  %>
  <center>
    <h3>Information of User's</h3>
    <table cellpadding="4" cellspacing="2" border="1" bgcolor="">
      <tr>
        <th>User Name</th>
        <th>Email Id</th>
      </tr>
      <tr>
        <%while(rs.next()){%>
          <td><input type="text" name="name" value="<%= rs.getString(1)%>" readonly="readonly">
          <td><input type="text" name="email" value="<%= rs.getString(2)%>" readonly="readonly">
          </tr>
        <%}%>
    </table>
  </center>
</form>

Now I want to save this data in a csv file(having an export option in it).

Any inputs will be appreciated.

Jacob Schoen
  • 14,034
  • 15
  • 82
  • 102
big zero
  • 610
  • 2
  • 8
  • 16

2 Answers2

10

here is a class you can using to export to CSV:

import java.io.FileWriter;
import java.io.IOException;
import User;

 public class GenerateCsv
 {


    private static void generateCsvFile(ArrayList<User> users)
    {
        String output = "Email, Name\n";

        for (User user in users) {
            output += user.getEmail() + ", " + user.getName() + "\n";
        }

        return output;
    }
 }

Working the MVC way

Here is how your code should be written:

Let's say you have a class called. User.java inside of which there is a static function called get all users

public class User {

    String name;
    String email;

    public static ArrayList<User> getAllUsers() {
        // returns all users
        ... 
    }

}

Then let's say you have a servlet called UsersServlet which get these users:

import javax.servlet.*;
import javax.servlet.http.*;

public class UsersServlet extends HttpServlet {

    public void doGet (HttpServletRequest   req, HttpServletResponse  res)
        throws ServletException, IOException {

        res.setContentType("application/csv");
        PrintWriter w = res.getWriter();

        ArrayList<User> users = Users.getAllUsers();

        w.prinln(GenerateCsv.generateCsvFile(users));

        w.flush();
        w.close();
    }

    public void doPost (HttpServletRequest  req, HttpServletResponse  res)
        throws ServletException, IOException {
        ...
    }
}

in your jsp, for example, you will have a simple anchor tag which calls the servlet (the servlets calls User.java, get data, forms them into a CSV and then outputs it to the browser...). Something like this would work:

<a href='/getCSV' > Export CSV </a>

but please note that you have to link the servlet to the url using web.xml:

<web-app>
    <servlet>
        <servlet-name>UsersServlet</servlet-name>
        <servlet-class>__package__.UsersServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>UsersServlet</servlet-name>
    <url-pattern>getCSV</url-pattern>
    </servlet-mapping>
</web-app>

EDIT: Writing to disk instead of sending to browser

 import java.io.FileWriter;
 import java.io.IOException;
 import User;

 public class GenerateCsv
 {


    private static void generateCsvFile(String fileName, ArrayList<User> users)
    {
           try
           {
                FileWriter writer = new FileWriter(fileName);

                writer.append("Email");
                writer.append(',');
                writer.append("Name");
                writer.append('\n');

                for (User user in users) {
                     writer.append(user.getEmail());
                     writer.append(',');
                     writer.append(user.getName());
                     writer.append('\n');
                }

                writer.flush();
                writer.close();
           } catch(IOException e) {
                 e.printStackTrace();
           } 
      }
 }
Rorchackh
  • 2,113
  • 5
  • 22
  • 38
  • 1
    It seems to me your html elements and braces ({ and ) are not well coordinated. pay attention to that! – Rorchackh Oct 31 '12 at 14:00
  • yeah, he needs to move that opening `` element inside the while like you have done. – Jacob Schoen Oct 31 '12 at 14:01
  • @Rorchackh thanks a lot for your contribution.And I create that class and I want to call it in onclick event button...so how will I implement it. + 1 more thing(i.e.) I know how to writing of serverside code in a servlet,but when I'll show dynamic value in a jsp page then how should I implement that serverside code in a servlet...could you provide some link on this context. – big zero Nov 01 '12 at 07:46
  • See my edit. Please know that there are too many ways you can actually do this by the MVC way is the best. Hope that makes things even clearer. I have also changed the helper class so this time it only returns a String instead of writing to a file. You can send that string to the browser directly. – Rorchackh Nov 01 '12 at 08:36
  • Thanks once again for your benchmark answer,I set it as a anewer,I'll keep it in mind while implement it,but I'm implementing it with your previous way(what you have showed),could you share any inputs on importing the csv file locally with the help of a button. – big zero Nov 01 '12 at 09:28
  • What do you mean by importing the CSV locally? downloading in to the browser? – Rorchackh Nov 01 '12 at 09:47
  • actually I want to save the csv file in my system. – big zero Nov 01 '12 at 10:59
  • Then you should be able to do that by modifying the the GenerateCsv class in my previous answer (see the the old version of this answer). you can modify the function __generateCsvFile__ to actually write to disk instead of returning the CSV result as a string. – Rorchackh Nov 01 '12 at 14:48
  • How to specify the file name here – Veshraj Joshi Apr 22 '18 at 16:12
  • It probably shouldn't come to a surprise that do many people think they can implement a csv parser/formatter correctly themselves instead of using a library. The problem is that almost nobody can :( No csv isn't just "separate the arbitrary text with commas and you're done". – Voo May 12 '18 at 22:52
2

It is generally bad practice to have code embedded in the JSP, and you would be better off using a servlet, java classes, or a web framework like Spring, JSF, Struts, etc...

However, using your example above. The easiest way would be to create another JSP page like below:

<%@page contentType="text/text" %>
<% 
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/apps","root","root");
Statement stmt = con.createStatement();
String sql = "select * from info;";
ResultSet rs = stmt.executeQuery(sql);
%>
<%
while(rs.next()){
  out.println("\"" + rs.getString(1) + "\", \"" + rs.getString(2) + "\"\n");
}%>
<% //cleanup and close db access %>

This sets the content type to be a text file, so the browser can display it properly. Then it iterates through your recordset and outputs a line with the two fields surrounded by quotes and ends each line with a \n newline character. Then, on your original page, you would just have a link to this new JSP page to download the CSV.

Alternately, you could use an existing library like OpenCSV. This would allow for more complicated needs and may also save headaches by handling escaping or special scenarios automatically.

jcern
  • 7,798
  • 4
  • 39
  • 47