原因可能是Java :(的知识不足),所以我问这个问题,
在这段代码中,我正在从jsp页面获取动态值:
<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>
现在,我想将此数据保存在一个csv文件中 (其中具有导出选项)。
任何输入将不胜感激。
这是您可以用来导出为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; } }
以MVC方式工作
这是编写代码的方式:
假设您有一个名为的类。 User.java 中有一个名为get all users的静态函数。
public class User { String name; String email; public static ArrayList<User> getAllUsers() { // returns all users ... } }
然后,假设您有一个名为UsersServlet的servlet,它可以获取这些用户:
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 { ... } }
例如,在您的jsp中,您将有一个简单的锚标记,该标记调用servlet(这些servlet调用User.java,获取数据,将它们形成CSV,然后将其输出到浏览器…)。这样的事情会起作用:
<a href='/getCSV' > Export CSV </a>
但请注意,您必须使用web.xml 将servlet链接到 url :
<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>
编辑:写入磁盘而不是发送到浏览器
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(); } } }