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) :
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");
%>
Information of User's
User Name | Email Id |
---|---|
Now I want to save this data in a csv file(having an export option in it).
Any inputs will be appreciated.
解决方案
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 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 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 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:
but please note that you have to link the servlet to the url using web.xml:
UsersServlet
__package__.UsersServlet
UsersServlet
getCSV
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 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();
}
}
}