How to export data in CSV format using Java?

前端 未结 2 1643
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-03 17:36

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) :

相关标签:
2条回答
  • 2021-01-03 17:57

    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();
               } 
          }
     }
    
    0 讨论(0)
  • 2021-01-03 17:57

    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.

    0 讨论(0)
提交回复
热议问题